define(['moment', 'sortablejs', 'module/moduleA/program/B01/custom_order/custom_order'], function (moment, Sortable) {
    return ['$scope', '$filter', '$stateParams', '$mdDialog', 'config', 'MMWService', '$calculater', '$datePicker', '$timeout', "$state", "$mddProvider", "customOrderService",
    function ($scope, $filter, $stateParams, $mdDialog, config, $MMWService, $calculater, $datePicker, $timeout, $state, $mddProvider, customOrderService) {
        // 20230911 modify by Alan for #136071: 增加跨頁選中功能
        let dispatch_detail_checked = []; // 未派工列表選中的暫存

        $scope.Mode = '';
        $scope.machineList = [];//區域內的機台列表
        $scope.machine_detail = [];
        $scope.machineList.PageConfig = {
            nowPage : 1,
            totlePage : 1,
            perPage : 10,
            perPageRow: 5
        };
        var item_no = ""; // 产品编号
        $scope.is_lock_sort = false;
        $scope.select_all_bool = false;
        $scope.roll_back_all_bool = false;
        $scope.order_by_mode = {name:"",sort:false};
        $scope.assigned_machine = ''; // 過濾已派工的設備編號或設備名稱
        $scope.acc_detail = [];
        $scope.ht_tr_bool = false; //M#95547 add by a991241234 熱處理 是否顯示爐量
        $scope.op_group_detail = [];
        $scope.pageSetting = { PageNumber: 1, PageRow: 25, TotalPage: 1 };
        $scope._objdispatch_detail = {
            PageConfig: {
                page_count: 25,
                page: 0,
                total_page: 0
            }
        }
        $scope.equipment_sort_mode_change = false;
        $scope.product_detail = [];
        // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
        $scope.area_detail = [];
        $scope.selectareaNo = "";
        $scope.isLine = "";
        $scope.selectWorkStation = '';
        $scope.selectWorkStationName = '';

        //20220916 add by 翰鴻 for M#118068        
        $scope.IIoT_Enable = false;
        $scope.dispatch_detail = [];
        $scope.selectSameOp = false
        $scope.init = function(){
            //20220916 add by 翰鴻 for M#118068
            if (
                $.grep(config.module, function (n, i) {
                    return n.name == "moduleIIoT"
                }).length > 0
            )
                $scope.IIoT_Enable = true;
            $scope.$root.menuList.forEach(function (menuItem) {
                //20220916 add by 翰鴻 for M#118068
                if ($scope.IIoT_Enable == false) {
                    if (menuItem.name == "IIoT0107" || menuItem.name == "IIoT0109") {
                        menuItem.isShow = false;
                    }
                }
            });
            // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
            $scope.showMode = "query"
            $scope.printList = []; // 列印詳情

            $scope.work_date = new Date();//工作時間
            $scope.order_by_mode = {name:"",sort:false};
            // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
            // step 1. 取得區域
            $scope.loadAreaInfo();
      
        };

        $scope.back = function(){
            $scope.$root.hideMenu();
            $scope.$root.changeProgram('home', true);
        };

        // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
        $scope.loadAreaInfo = function() {
            // 取得區域列表
            $MMWService.pageNumberInfoGet({
                form_name: 'PageNo_51',
                query_condition_info: [
                    {column_name:'A.MASTERNO', query_mode:'0', value:config.cache.account, merge_condition_model:'AND'}
                ],
            }, function(itemList){
                if(itemList.length <= 0) {
                    $scope.$root.showAlert($filter('translate')('A02.msg.noArea1'));
                    return;
                }

                $scope.area_detail = itemList;
                $scope.selectareaNo = $scope.area_detail[0].page_no;
                $scope.selectareaName = $scope.area_detail[0].page_no + ' (' + $scope.area_detail[0].page_name + ')';
                $scope.isLine = $scope.area_detail[0].area_type||'0';
                $scope.selectWorkStation = '';
                $scope.selectWorkStationName = '';
                $scope.op_group_detail = [];
                //step 2. 把第一筆區域當成預設值並帶入search 內查詢出資訊
                // 先查op_list 再查 undispatched_list跟machine_statistcs_list
                search({ return_type: '1000' }, function() {
                    search({ return_type: '0110' })
                });
            });
        }

        // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
        $scope.loadMyFavorites = function() {
            $MMWService.showQueryListPNIG({
                form_name: 'PageNo_50',
                mode:'M',
                key:'page_no',
                header : [
                    {label: $filter('translate')('common.queryList.area_c'), code:'page_no'},
                    {label: $filter('translate')('common.queryList.area_n'), code:'page_name'}
                ],
                selectKey:{key:'isselect', true: '1', false: '0'},
                setCondition:function(conditions){
                    conditions.push({column_name:'MASTERNO', query_mode:'0', value:config.cache.account, merge_condition_model:'AND' });
                    return conditions;
                },
                confirm: function(selectItem, dialog){
                    // 向数据库插入我的最爱数据信息
                    var content = {
                        master_no: config.cache.account, // 用户编号
                        master_type: 7,
                        favourite_user_area:[]
                    };
                    selectItem.forEach(function(item){
                        if(item.isselect == '1'){
                            content.favourite_user_area.push({area_no:item.page_no});
                        }
                    });
                    if(content.favourite_user_area.length == 0){
                        $scope.$root.showAlert($filter('translate')('A02.msg.lessThan'));
                    }else{
                        $MMWService.sendToServer({
                            uri: 'ServicesSTD.Module_SYS.favourite_machine_process',
                            content : content,
                            success : function(data){
                                dialog.hide();
                                $scope.loadAreaInfo();
                            }
                        });
                    }
                }
            });
        };

        // 实体分页查询功能实现 20221116 modify by  for M#18991
        // 20240117 modify by Alan for #156241: 補上6.0搬遷時缺少的實體分頁查詢功能
        let targetData;
        $scope.blurSearch = function (e) {
            const keycode = window.event ? e.keyCode : e.which;
            if (keycode == 13) {
                $scope.pageSetting.PageNumber = 1;
                targetData = {
                    qty: $scope._objdispatch_detail.filterColumns.qty || 0,
                    plot_start_time: $scope._objdispatch_detail.filterColumns.plot_start_time,
                    plot_end_time: $scope._objdispatch_detail.filterColumns.plot_end_time,
                    item_no: $scope._objdispatch_detail.filterColumns.item_no,
                    item_name: $scope._objdispatch_detail.filterColumns.item_name,
                    item_spec: $scope._objdispatch_detail.filterColumns.item_spec,
                    mono_date: $scope._objdispatch_detail.filterColumns.mono_date,
                    op_no: $scope._objdispatch_detail.filterColumns.op_no,
                    op_name: $scope._objdispatch_detail.filterColumns.op_name,
                    wo_no: $scope._objdispatch_detail.filterColumns.wo_no,
                    plot_no: $scope._objdispatch_detail.filterColumns.plot_no,
                }
                search({ return_type: '0110' });
            }
        }

        // 20230911 modify by Alan for #136071: 增加跨頁選中功能
        // 增加清除已選暫存的功能
        /**
         * @param {Object} option - 查詢條件
         * @param {Function} feedback - 回調函式
         * @param {String} option.return_type - 4位字串，每一位代表一種查詢結果，</br>
         * 
         * 1000 => op_list.
         * 
         * 0100 => undispatched_list </br>
         * 
         * 0010 => machine_statistcs_list
         * 
         * 0001 => dispatched_list
         * @param {Boolean} option.cleanCache - 是否清除已選暫存，預設為清除
         */
        function search(option, feedback){
            // 20240313 modify by shiwl for # 0159423: 测试区在线人员平台派工界面设备查询显示异常  切换分支后重新查询重置页码
            $scope.machineList.PageConfig = {
                nowPage : 1,
                totlePage : 1,
                perPage : 10,
                perPageRow: 5
            };  

            // 檢查是否有區域訊息
            if($scope.area_detail.length == 0){
                // 派工区域尚未设定我的最爱，请问是否要现在设定？
                var msg = $filter('translate')('A02.alert.msg2');
                $scope.$root.showConfirm(msg, function(dialog)
                {
                   dialog.hide();
                   $scope.loadMyFavorites();
                   
                });
                return;
            }

            let content = angular.merge(
                {
                    area_no: $scope.selectareaNo,
                    lst_opno: [],
                    pageSetting: $scope.pageSetting,
                    work_date: moment($scope.work_date).format("YYYY-MM-DD"),
                    machine_statistics_condition: {
                        wo_no: "",
                        plot_no: "",
                        machine_no: "",
                        is_capacity: true
                    },
                    dispatched_condition: {
                        wo_no: "",
                        plot_no: "",
                        machine_no: "",
                        
                    },
                    undispatched_condition: {
                        wo_no: "",
                        plot_no: "",
                        is_user_defined_column: false,
                        is_accessory: true
                    },
                },
                option
            );

            // 实体分页查询 20221116 
            var target = Object.assign(content.undispatched_condition, targetData);
            content.undispatched_condition = target;
           
            // undispatched_list或machine_statistcs_list或dispatched_list 要帶lst_opno
            if(content.return_type.charAt(1) === '1' 
                || content.return_type.charAt(2) === '1'
                || content.return_type.charAt(3) === '1') {
                content = angular.merge(content,{
                    lst_opno: $scope.op_group_detail.map(item => item.op_no)
                });
            }
            
            // undispatched_list 未派列表
            if(content.return_type.charAt(1) === '1') {
                content = angular.merge(
                    content,
                    {
                        undispatched_condition: {
                            wo_no: $scope.unassigned_wo_no || content.undispatched_condition.wo_no || "",
                            plot_no: $scope.unassigned_plot_no || content.undispatched_condition.plot_no || "",
                            is_user_defined_column: false,
                            is_accessory: true
                        }
                    }
                );
                // 取得未派排序設定
                content.undispatched_condition.sort = customOrderService.getSettings('dispatch_detail');
            }

            // machine_statistcs_list 設備列表
            if(content.return_type.charAt(2) === '1') {
                content = angular.merge(
                    content,
                    {
                        machine_statistics_condition: {
                            wo_no: $scope.assigned_wo_no || "",
                            plot_no: $scope.assigned_plot_no || "",
                            machine_no: $scope.assigned_machine || "",
                            is_capacity: true
                        },
                    }
                );
            }

            // dispatched_list 已派列表
            if(content.return_type.charAt(3) === '1') {
                content = angular.merge(
                    content,
                    {
                        dispatched_condition: {
                            wo_no: $scope.assigned_wo_no || "",
                            plot_no: $scope.assigned_plot_no || "",
                            machine_no: $scope.assigned_machine || "",
                        },
                    }
                );
            }

            //當有設定已派工查詢條件時，不可變更已派工順序
            $scope.is_lock_sort = (content.dispatched_condition.wo_no == '' && content.dispatched_condition.plot_no == '');

            $MMWService.sendToServer({
               //  修复首次加载提示 Cannot read property 'funcs' of undefined 问题 20230210 modify by shiwl
                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_new_get',
                content: content,
                success: function (data) {
                    // 20240221 modify by wenwei for M#153610
                    $scope.product_detail = data.product_detail
                    var errorMsg = '';
                    // op_list 作業站列表
                    if(content.return_type.charAt(0) === '1'){
                        //M#95547 熱處理優化 爐量顯示
                        var op_has_ht = 0;  // 熱處理 作業站計數
                        $scope.selectWorkStationName = '';
                        $scope.op_group_detail = data.op_list;
                        if($scope.op_group_detail && $scope.op_group_detail.length>0){
                            //M#95547 熱處理優化 爐量顯示
                            var op_has_ht = 0;  // 熱處理 作業站計數
                            $scope.op_group_detail.forEach(function(item){
                                if(item.is_select == 'true')
                                    $scope.selectWorkStationName += item.op_name + ' \\ ';
                                if(item.plugin == 1) // plugin == 1 == 熱處理 作業站
                                    op_has_ht++;
                            });
                            //判斷是否有熱處理作業站  大於 0 顯示爐量 
                            if(op_has_ht > 0)
                                $scope.ht_tr_bool = true;
                            else
                                $scope.ht_tr_bool = false;
                            $scope.selectWorkStationName = $scope.selectWorkStationName.substr(0, $scope.selectWorkStationName.length-3);
                        }
                    }

                    // undispatched_list 未派列表
                    if(content.return_type.charAt(1) === '1') {
                        // 20230911 modify by Alan for #136071: 有查詢未派時，才更新頁數
                        $scope.pageSetting.TotalPage = data.undispatched_list_totalPage;
                        $scope._objdispatch_detail.PageConfig.total_page = data.undispatched_list_totalPage
                        // 20230213 modify by Alan for #127915: 可派工数量为0的生产任务不显示在界面上
                        $scope.dispatch_detail = data.undispatched_list.filter(item => item.qty > 0); 
                        // 20230911 modify by Alan for #136071: 預設清除已選暫存
                        if (option.cleanCache === undefined || option.cleanCache) {
                            dispatch_detail_checked = [];
                        }
                        if($scope.dispatch_detail.length == 0){
                            if(content.dispatched_condition.wo_no == ''
                                && content.dispatched_condition.plot_no == ''){
                                errorMsg += $filter('translate')('A02.msg.B0201first')+'<br>';
                            } else {
                                errorMsg += $filter('translate')('common.msg.no_data')+'<br>';
                            }
                        } else {
                            // 20230911 modify by Alan for #136071: 增加跨頁選中功能
                            // 從暫存中取出選擇的資料，還原到已派工列表
                            for(let item of dispatch_detail_checked) {
                                if(item._page === $scope.pageSetting.PageNumber) {
                                    let index = $scope.dispatch_detail.findIndex(temp => temp.plot_no == item.plot_no && temp.op_no == item.op_no);
                                    if (index != -1) {
                                        $scope.dispatch_detail[index].isSelect = true;
                                    } else {
                                        $scope.$root.showAlert($filter('translate')('A07.showAlert.undispatch_changed'));
                                        dispatch_detail_checked = [];
                                        $scope.Mode = '';
                                        return;
                                    }
                                }
                            }
                            
                            let thisPageChecked = $scope.dispatch_detail.filter(item => item.isSelect);
                            $scope.select_all_bool = thisPageChecked.length === $scope.dispatch_detail.length;
                        }
                    }

                    // machine_statistcs_list 設備列表
                    if(content.return_type.charAt(2) === '1'){

                        // 20200319 modify by WeiTing for M#62127 - 增加過濾已派工的設備編號或設備名稱。
                        if($scope.assigned_machine == ''){
                            $scope.machine_detail = data.machine_statistcs_list;
                        } else {
                            var machine_detail_filter = [];
                            data.machine_statistcs_list.forEach(function(item){
                                if(item.machine_no.indexOf($scope.assigned_machine) != -1 
                                || item.machine_name.indexOf($scope.assigned_machine) != -1){
                                    machine_detail_filter.push(item);
                                } 
                            });
                            $scope.machine_detail = machine_detail_filter;
                        };

                        if($scope.machine_detail.length == 0){
                            if(content.machine_statistics_condition.wo_no == ''
                                && content.machine_statistics_condition.plot_no == ''){
                                errorMsg += $filter('translate')('A02.msg.A01first')+'<br>';
                            } else {
                                errorMsg += $filter('translate')('common.msg.no_data')+'<br>';
                            }
                            $scope.machineList.PageConfig.totlePage = 1;
                        } else {
                            //算出機台總筆數
                            $scope.machineList.PageConfig.totlePage = Math.ceil($scope.machine_detail.length/$scope.machineList.PageConfig.perPageRow);
                        }
                    }

                    // dispatched_list 已派列表
                    if(content.return_type.charAt(3) === '1'){

                        // 20200319 modify by WeiTing for M#62127 - 增加過濾已派工的設備編號或設備名稱。
                        if($scope.assigned_machine == ''){
                            $scope.machine_detail = data.machine_statistcs_list;
                        } else {
                            var machine_detail_filter = [];
                            data.machine_statistcs_list.forEach(function(item){
                                if(item.machine_no.indexOf($scope.assigned_machine) != -1 
                                || item.machine_name.indexOf($scope.assigned_machine) != -1){
                                    machine_detail_filter.push(item);
                                } 
                            });
                            $scope.machine_detail = machine_detail_filter;
                        };

                        if($scope.machine_detail.length == 0){
                            if(content.dispatched_condition.wo_no == ''
                                && content.dispatched_condition.plot_no == ''){
                                errorMsg += $filter('translate')('A02.msg.A01first')+'<br>';
                            } else {
                                errorMsg += $filter('translate')('common.msg.no_data')+'<br>';
                            }
                            $scope.machineList.PageConfig.totlePage = 1;
                        } else {
                            //算出機台總筆數
                            $scope.machineList.PageConfig.totlePage = Math.ceil($scope.machine_detail.length/$scope.machineList.PageConfig.perPageRow);
                        }
                    }

                    if(errorMsg) {
                        $scope.$root.showAlert(errorMsg);
                    }

                    if(typeof feedback === 'function') {
                        feedback();
                    }
                    
                    EquipmentSortAction();
                }
            });
        }

        // 20230204 modify by Alan for #127154: [MSSQL][sMOM][H5][派工作业]页数错误
        //未派工查詢
        $scope.unassigned_search = function(){
           // 查询数据初始化
           $scope.pageSetting.PageNumber = 1;
           $scope._objdispatch_detail.PageConfig.page = $scope.pageSetting.PageNumber - 1;
             targetData = {
                     qty: $scope._objdispatch_detail.filterColumns['qty'] || 0,
                     plot_start_time: $scope._objdispatch_detail.filterColumns['plot_start_time'],
                     plot_end_time: $scope._objdispatch_detail.filterColumns['plot_end_time'],
                     item_no: $scope._objdispatch_detail.filterColumns['item_no'],
                     item_name : $scope._objdispatch_detail.filterColumns['item_name'],
                     item_spec: $scope._objdispatch_detail.filterColumns['item_spec'],
                     mono_date : $scope._objdispatch_detail.filterColumns['mono_date'],
                     op_no: $scope._objdispatch_detail.filterColumns['op_no'],  
                     op_name:$scope._objdispatch_detail.filterColumns['op_name'],
                     wo_no: $scope._objdispatch_detail.filterColumns['wo_no'],
                     plot_no: $scope._objdispatch_detail.filterColumns['plot_no'],
             }; 
            search({return_type:'0100'});
        };

        //清除未派工查詢
        $scope.unassigned_clear = function(){
            $scope.unassigned_wo_no = '';
            $scope.unassigned_plot_no = '';
            $scope.assigned_machine = ''; 
            $scope.unassigned_search();
        };

        //已派工查詢
        $scope.assigned_search = function(){
            if($scope.Mode == 'MachineExpend'){
                initMachineExpend($scope.selectMachine);
            } else {
                search({return_type:'0010'});
            }
        };

        //清除已派工查詢
        $scope.assigned_clear = function(){
            $scope.assigned_wo_no = '';
            $scope.assigned_plot_no = '';
            $scope.assigned_search();
        };

        var dis_date_separate_action = function()
        {
            if($scope.dispatched_detail && $scope.dispatched_detail.length > 0)
            {
                $scope.dispatched_detail.forEach(function(item){
                    if(item.dis_plot_start_time && item.dis_plot_start_time != "")
                    {
                        var str_list = item.dis_plot_start_time.split(" ");
                        if(str_list.length >= 2)
                        {
                            item.dis_start_date = str_list[0];
                            item.dis_start_time = str_list[1];
                        }
                    }
                    else
                    {
                        item.dis_start_date = moment($scope.work_date).format('YYYY-MM-DD');
                        item.dis_start_time = "00:00:00";
                    }
                    if(item.dis_plot_end_time && item.dis_plot_end_time != "")
                    {
                        var str_list = item.dis_plot_end_time.split(" ");
                        if(str_list.length >= 2)
                        {
                            item.dis_end_date = str_list[0];
                            item.dis_end_time = str_list[1];
                        }
                    }
                    else
                    {
                        item.dis_end_date = moment($scope.work_date).format('YYYY-MM-DD');
                        item.dis_end_time = "00:00:00";
                    }
                });
            }
        }

        $scope.time_open_set = function(event,detail,time,type)
        {
            var target = event.currentTarget;
            angular.element(target).addClass('is-focus');
            var rule = /^\d{2}:\d{2}:\d{2}$/;
            if(rule.test(time) == false)
                time = "00:00:00";
            $calculater.open(function(timeDisplay,dialog)
            { 
        	    angular.element(target).removeClass('is-focus');
                var hour = timeDisplay.hour, min = timeDisplay.minute, sec = timeDisplay.second;
               
                var time_str = hour+":"+min+":"+sec;
                if((0 <= (+hour) && (+hour) < 24) && 
                (0 <= (+min) && (+min) < 60) && 
                (0 <= (+sec) && (+sec) < 60) && rule.test(time_str))
                {
                    var content = {};
                    var time_check = true;
                    content.need_dispatch_plot_detail = [];
                    if(type == 4)
                    {
                        detail.dis_start_time = time_str;
                        detail.dis_time = detail.dis_start_date+" "+time_str;
                        content.work_mode = "4";
                    }
                    else if(type == 5)
                    {
                        detail.dis_time = detail.dis_end_date+" "+time_str;
                        content.work_mode = "5";
                        if(Date.parse(detail.dis_plot_start_time) > Date.parse(detail.dis_time))
                            time_check = false;
                        if(time_check)
                            detail.dis_end_time = time_str; 
                    }
                    if(time_check)
                    {
                        content.need_dispatch_plot_detail.push({
                            plot_no:detail.plot_no,
                            op_no:detail.op_no,
                            qty:detail.plot_qty,
                            mo_no:detail.mo_no,
                            machine_no:$scope.selectMachine.machine_no,
                            plot_start_time:detail.plot_start_time,
                            plot_end_time:detail.plot_end_time,
                            dis_time:detail.dis_time
                        });
                        content.dispatch_to = [];
                        content.with_draw_mode = "0";
                        content.dispatch_day = moment($scope.work_date).format('YYYY-MM-DD');
                        dispatch_area_info_set_process(content, function() {
                            search({return_type:'0010'}, function(){
                                $scope.$root.showToast($filter('translate')('A05.js.success'));
                                $scope.Mode = 'MachineExpend';
                                var machine = $filter('filter')($scope.machine_detail, {machine_no:$scope.selectMachine.machine_no});
                                if(machine!=undefined && machine.length > 0)
                                {
                                    $scope.selectMachine = machine[0];
                                }
                                initMachineExpend($scope.selectMachine);
                            });
                        })
                    }
                    else
                        $scope.$root.showAlert($filter('translate')('A02.alert.time_error_msg'));
                    
                    angular.element(target).removeClass('is-focus');
                    dialog.hide();
                } else 
                {
                    if($scope.$root.showAlert)
                        $scope.$root.showAlert($filter('translate')('common.msg.time_format_error'));
                }
            },
            function(dialog){
    		    angular.element(target).removeClass('is-focus');
    		    dialog.hide();
    	    },
    	    {
                type:"date",
                defaultNum : time,
                title:$filter('translate')('common.msg.select_time'),
    		    decimal : false
    	    });
        };

        // 20230204 modify by Alan for #127154: [MSSQL][sMOM][H5][派工作业]页数错误
        //選擇區域
        $scope.loadAreaList = function(){
            $scope.pageSetting.PageNumber = 1;
            $scope._objdispatch_detail.PageConfig.page = $scope.pageSetting.PageNumber - 1;
            // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
            if($scope.area_detail.length == 0){
                var msg = $filter('translate')('A02.alert.msg2');
                $scope.$root.showConfirm(msg, function(dialog)
                {
                   dialog.hide();
                   $scope.loadMyFavorites();
                   
                });
                return;
            }

            // 20230313 modify by Alan for #129679: 清空查詢條件
            $scope.$root.showQueryList({
                key:'page_no',
                header : [
                    {label: $filter('translate')('common.queryList.area_c'), code:'page_no'},
                    {label: $filter('translate')('common.queryList.area_n'), code:'page_name'}
                ],
                query: function(conditions, feedback){
                    feedback($scope.area_detail);
                },
                selectCode:$scope.selectareaNo||'',
                confirm: function(selectItem, dialog){
                    $scope.selectareaNo = selectItem.page_no;
                    $scope.selectareaName = selectItem.page_no + ' (' + selectItem.page_name + ')';
                    $scope.op_group_detail = [];
                    $scope.isLine = selectItem.area_type||'0';
                    $scope.unassigned_wo_no = '';
                    $scope.unassigned_plot_no = '';
                    $scope.assigned_wo_no = "";
                    $scope.assigned_plot_no = "";
                    $scope.assigned_machine = "";
                    dialog.hide();

                    // 先查op_list 再查 undispatched_list跟machine_statistcs_list
                    search({ return_type: '1000' }, function() {
                        search({ return_type: '0110' })
                    });
                }
            });
        };

        // 20230204 modify by Alan for #127154: [MSSQL][sMOM][H5][派工作业]页数错误
        //選擇作業站
        $scope.loadWorkStationList = function(){
            $scope.pageSetting.PageNumber = 1;
            $scope._objdispatch_detail.PageConfig.page = $scope.pageSetting.PageNumber - 1;
            const content = {
                area_no: $scope.selectareaNo,
                return_type: "1000"
            };
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_new_get',
                content : content,
                success : function(data){
                    if(data && data.op_list)
                    {
                        $scope.op_list = data.op_list
                    }
                    $scope.$root.showQueryList({
                        mode:'M',
                        key:'op_no',
                        header : [
                            {label: $filter('translate')('common.queryList.op_c'), code:'op_no'},
                            {label: $filter('translate')('common.queryList.op_n'), code:'op_name'}
                        ],
                        query: function(conditions, feedback){
                            feedback($scope.op_list);
                        },
                        selectKey:{key:'is_select', true:'true', false:'false'},
                        confirm: function(selectItem, dialog){
                            // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
                            var content = {
                                master_no: $scope.selectareaNo,
                                master_type: 8,
                                favourite_user_opno:[],
                                user_no: config.cache.account // 用户编号
                            };
                            var selectWorkStationName = '';
                            selectItem.forEach(function(item){
                                if(item.is_select == 'true'){
                                    // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
                                    content.favourite_user_opno.push({op_no:item.op_no});
        
                                    selectWorkStationName += item.op_name + ' \\ ';
                                }
                            });
                            selectWorkStationName = selectWorkStationName.substring(0, selectWorkStationName.length -3);
        
                            $MMWService.sendToServer({
                                uri: 'ServicesSTD.Module_SYS.favourite_machine_process',
                                content : content,
                                success : function(data){
                                    $scope.selectWorkStation = '';
                                    $scope.selectWorkStationName = selectWorkStationName;
                                    dialog.hide();
                                    search({ return_type: '0110' });
                                }
                            });
                        }
                    });
                }
            });
        };

        function dispatch_area_info_new_get(option, callback) {
            let content = angular.merge(
                {
                    area_no: $scope.selectareaNo,
                    lst_opno: [],
                    pageSetting:$scope.pageSetting,
                    work_date: moment($scope.work_date).format("YYYY-MM-DD"),
                    machine_statistics_condition: {
                        wo_no: $scope.unassigned_wo_no || "",
                        plot_no: $scope.unassigned_plot_no || "",
                    },
                    dispatched_condition: {
                        wo_no: $scope.assigned_wo_no || "",
                        plot_no: $scope.assigned_plot_no || "",
                    },
                    undispatched_condition: {
                        wo_no: "",
                        plot_no: "",
                        is_user_defined_column: false,
                        is_accessory: true
                    },
                },
                option
            );
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_new_get',
                content : content,
                success : function(data){
                    if(typeof callback === 'function') {
                        callback(data);
                    }
                }
            });
        }

        // 20230911 modify by Alan for #136071: 切換日期不清除勾選狀態
        $scope.changeDate = function(){
            $datePicker.open($scope.work_date,
            function(dialog){
                $scope.work_date = dialog.datePacker.pickDate;
                dialog.hide();
                if($scope.Mode == 'MachineExpend'){
                    initMachineExpend($scope.selectMachine);
                } else {
                    search({ return_type: '0010'});
                }
            },
            function(dialog){
                dialog.hide();
            },{});
        };

        // 20230204 modify by Alan for #127154: [MSSQL][sMOM][H5][派工作业]页数错误
        $scope.prevDate = function(){
            $scope.pageSetting.PageNumber = 1;
            $scope._objdispatch_detail.PageConfig.page = $scope.pageSetting.PageNumber - 1;
            $scope.work_date = moment($scope.work_date).add(-1,'d').toDate();
            if($scope.Mode == 'MachineExpend'){
                initMachineExpend($scope.selectMachine);
            } else {
                search({ return_type: '0010'});
            }
        };

        // 20230204 modify by Alan for #127154: [MSSQL][sMOM][H5][派工作业]页数错误
        $scope.nextDate = function(){
            $scope.pageSetting.PageNumber = 1;
            $scope._objdispatch_detail.PageConfig.page = $scope.pageSetting.PageNumber - 1;
            $scope.work_date = moment($scope.work_date).add(1, 'd').toDate();
            if($scope.Mode == 'MachineExpend'){
                initMachineExpend($scope.selectMachine);
            } else {
                search({ return_type: '0010'});
            }
        };

        $scope.itemSelect = function(index, work){
            if(work.status == '0'){
                // 此任務在智派工納入派工，不可重複勾選！
                return $scope.$root.showAlert($filter('translate')('A02.msg.sjds_dispatch_can_not_select')); 
            }

            // 20230911 modify by Alan for #136071: 增加跨頁選中功能
            // 檢查勾選的任務是否已經在已選派工列表中
            let targetIndex = dispatch_detail_checked.findIndex(temp => temp.plot_no == work.plot_no && temp.op_no == work.op_no);
            // 20240221 modify by wenwei for M#153610
            if(work.isSelect || work.isSelect != undefined){
                work.isSelect = undefined;
                $scope.select_all_bool = false;
                if (targetIndex != -1) {
                    dispatch_detail_checked.splice(targetIndex, 1);
                }
            }else{
                work.isSelect = true;
                if (targetIndex == -1) {
                    // 保存目前頁數，提供後續比對數據異動
                    let temp = angular.merge({}, work, { _page: $scope.pageSetting.PageNumber});
                    dispatch_detail_checked.push(temp);
                }
            }

            // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
            if (dispatch_detail_checked.length == 0) {
                $scope.Mode = '';
                $scope.showMode = 'query';
            } else {
                $scope.Mode = 'EditSendWork';
                $scope.showMode = 'preview'
            }

            EquipmentSortAction();
        };

        $scope.itemAllAction = function()
        {
            if($scope.dispatch_detail.length <= 0)
                return;
              //  20231128 modify by shiwl for #	0154887: 【测试区】把派工界面的待派工数据过滤只剩下3笔，全选派工没有只派3笔，会把所有的待派工数据都派下去
             $scope.dispatch_detail= $filter('filter')($scope.dispatch_detail,$scope._objdispatch_detail.filterColumns);
            for(var i in $scope.dispatch_detail)
            {
                // 20230911 modify by Alan for #136071: 增加跨頁選中功能
                // 檢查勾選的任務是否已經在已選派工列表中
                let targetIndex = dispatch_detail_checked.findIndex(temp => temp.plot_no == $scope.dispatch_detail[i].plot_no && temp.op_no == $scope.dispatch_detail[i].op_no);
                if ($scope.select_all_bool) {
                    $scope.dispatch_detail[i].isSelect = false;
                    if (targetIndex != -1) {
                        dispatch_detail_checked.splice(targetIndex, 1);
                    }
                } else {
                    // 狀態 0 代表任務在智派工納入派工，不可勾選！
                    if ($scope.dispatch_detail[i].status == '0') {
                        $scope.dispatch_detail[i].isSelect = false;
                    } else {
                        if (targetIndex == -1) {
                            $scope.dispatch_detail[i].isSelect = true;
                            // 保存目前頁數，提供後續比對數據異動
                            let temp = angular.merge({}, $scope.dispatch_detail[i], { _page: $scope.pageSetting.PageNumber});
                            dispatch_detail_checked.push(temp);
                        }
                    }
                }
            }

            $scope.select_all_bool = !$scope.select_all_bool; 
            // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
            if (dispatch_detail_checked.length === 0)
            {
                $scope.showMode = "query"
                $scope.Mode = '';
            }
            else
            {
                $scope.showMode = "preview"  
                $scope.Mode = 'EditSendWork';
            }
        };

        // 20230911 modify by Alan for #136071: 增加跨頁選中功能
        $scope.SelectedInfo = {
            // 本页选中：　0
            current(){
                let amount = $filter('filter')($scope.dispatch_detail, { isSelect: true }).length;
                return $filter('translate')('A07.selected_info.current', { amount });
            },
            // 合计选中：　0
            total() {
                let amount = $filter('filter')(dispatch_detail_checked, { isSelect: true }).length;
                return $filter('translate')('A07.selected_info.total', { amount });
            },
        };

        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
        var pdf_url;
        $scope.preview = function(){
            var plot_detail = [];
            if($scope.Mode == 'Rollback'){
                $scope.dispatched_detail.forEach(function(item){
                    if(item.isSelect)
                    {
                        var info = {
                            plot_no: item.plot_no,
                            plot_qty: item.qty
                        }
                        plot_detail.push(info);
                    }
                });
            }else{
                var dispach_detail = $filter('filter')($scope.dispatch_detail,$scope.dispatch_filter);
                dispach_detail.forEach(function(detail, index){
                    if(detail.isSelect){
                        var info = {
                            plot_no: detail.plot_no,
                            plot_qty: detail.qty
                        }
                        plot_detail.push(info);
                    }
                });
            }

            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.runcard_pdf_get',
                content : {
                    course:($scope.show_history?'1':'0'),
                    plot_detail : plot_detail
                },
                success : function(data){

                    for(var i = 0; i < plot_detail.length; i++){
                        $scope.printList.push({
                            printNo: plot_detail[i].plot_no,
                            printType: '1' // 1: 流程卡打印 + 生產批開立; 3: 條碼標籤打印(補印); 4: 外包單 - 出貨打印; 5. 叫修作業;
                        });
                    }

                    pdf_url = data.runcard_pdf_get[0].url_pdf;
                    if(pdf_url.indexOf('http://') == -1){
                        pdf_url = 'http://'+config.server.ip+':'+config.server.port+ pdf_url;
                    }
                    if(config.setting.outsidePDF == 'Y'){
                        var fs = window.nodeRequire('fs'), RuncardPath;
                        try{
                            // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                            const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                            RuncardPath = remote.app.getAppPath();
                        }catch(e){
                            RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
                        }
                        RuncardPath += '\\www\\Runcard';
                        if(!fs.existsSync(RuncardPath)){
                            fs.mkdirSync(RuncardPath);
                        }

                        // 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
                        // 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                        fs.readdirSync(RuncardPath, (err, files) => {
                            if (err) {
                                console.log(err);
                            }
                            //listing all files using forEach
                            files.forEach((file) => {
                                // Do whatever you want to do with the file
                                fs.unlink(RuncardPath + '/' + file, (err) => {
                                    if (err) {
                                        console.debug(err);
                                    }
                                })
                            });
                        })

                        // 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
                        let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
                        $scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
                            // 20230807 modify by Alan for#130433 : electron升版後，shell.openItem改成shell.openPath
                            const { shell } = window.nodeRequire('electron');
                            shell.openItem ? shell.openItem(dist_path) : shell.openPath(dist_path);
                        });
                    } else {
                        showPDFViewer(pdf_url);
                    }
                }
            });
        };

        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
        function showPDFViewer(pdf_url){
            try{
                window.nodeRequire('nw.gui').Window.open(pdf_url, {
                    title:'PDF Viewer',
                    show: false,
                    icon:'icon/icon.png',
                    focus:true
                }, function(win) {
                    win.on('loaded', function(){
                        win.show();
                        win.print();
                    });
                });
            } catch (e){
                $scope.showMode = 'print';
                document.getElementById('kmi-pdf-panel').src = 'JSplugins/pdfjs/web/viewer.html?file='+pdf_url+'&openfile=false&viewbookmark=false&printfile=false&download=false#zoom=page-width';
            }
        }

        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
        $scope.print = function(){
            if(window.nodeRequire){
                var sumatraPDF = window.nodeRequire('sumatra-pdf');
                if(sumatraPDF){
                    var fs = window.nodeRequire('fs'), RuncardPath;
                    try{
                        // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                        const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                        RuncardPath = remote.app.getAppPath();
                    }catch(e){
                        RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
                    }
                    RuncardPath += '\\www\\Runcard';
                    if(!fs.existsSync(RuncardPath)){
                        fs.mkdirSync(RuncardPath);
                    }

                    // 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
                    // 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                    fs.readdirSync(RuncardPath, (err, files) => {
                        if (err) {
                            console.log(err);
                        }
                        //listing all files using forEach
                        files.forEach((file) => {
                            // Do whatever you want to do with the file
                            fs.unlink(RuncardPath + '/' + file, (err) => {
                                if (err) {
                                    console.debug(err);
                                }
                            })
                        });
                    })

                    // 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
                    let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
                    $scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
                        $scope.$root.showLoading();
                        window.nodeRequire('sumatra-pdf').printWithSettings({
                            path: dist_path,
                            success:function(){
                                printWiplogProcess(); // 列印完成後，需把列印詳情回送給後台做記錄
                                $scope.$root.hideLoading();
                                $scope.$root.showToast($filter('translate')('common.msg.success'));
                            },
                            error:function(error){
                                // 20201104 modify by WeiTing for M#77013 - 不清楚為何在實際列印後，有列印成一張紙或輸出成 PDF檔案時，都會執行 error區域，所以目前 error區域也先當列印完成後，把列印詳情回送給後台做記錄。
                                printWiplogProcess(); // 列印完成後，需把列印詳情回送給後台做記錄
                                $scope.$root.hideLoading();
                                $scope.$root.showToast($filter('translate')('common.msg.success'));
                                //console.error(error);
                            }
                        });
                    });
                } else {
                    window.frames['kmi-pdf-panel'].pdf_print();
                }
            } else {
                window.frames['kmi-pdf-panel'].pdf_print();
            }
            /*
            if(config.setting.printSetting){
                $PrintSetting.init({
                    callback:function(settings){
                        window.frames['kmi-pdf-panel'].pdf_print(settings);
                    }
                });
            } else {
                window.frames['kmi-pdf-panel'].pdf_print();
            }
            */
        };

        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
        $scope.download = function(){
            window.frames['kmi-pdf-panel'].pdf_download();
        };

        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
        $scope.cancel = function(){
            if($scope.Mode == 'Rollback'){
                $scope.showMode = 'query';
            }else{
                $scope.showMode = 'preview';
            }
            document.getElementById('kmi-pdf-panel').src = '';
            $scope.printList = [];
        };

        // 20201216 ADD FOR M#83236-1
        // 列印完成後，需把列印詳情回送給後台做記錄
		function printWiplogProcess(){
			$MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SN.print_wiplog_process',
				content : {
                    printList: $scope.printList
                },
				success : function(){
                    $scope.printList = [];
                }
			});
        }
        
        // 20230620 modify by Alan for #132192: 修正設備狀態
        $scope.machineStatus = function (status) {
            return 'status_' + convertMachineStatus(status);
        };

        $scope.machineStatusDisplay = function (status) {
            const key = "common.machine.status." + convertMachineStatus(status);
            return $filter("translate")(key).substring(0, 1);
        };

        function convertMachineStatus(status) {
            const convertMap = {
                3: "6",
                4: "3",
                6: "7",
                7: "4",
            };

            return convertMap[status] || status.toString();
        }

        $scope.selectMachine = undefined;
        $scope.getMachineList = function(){
            var start = ($scope.machineList.PageConfig.nowPage - 1)*$scope.machineList.PageConfig.perPageRow;
            var end = ($scope.machineList.PageConfig.nowPage)*$scope.machineList.PageConfig.perPageRow;
           // $scope.machine_detail= $filter('orderBy')($scope.machine_detail, 'machine_no', false); // 20231218 modify by shiwl for M#0153457: 派工排序乱序
            return $scope.machine_detail.slice(start,end);
        };

        $scope.prevPageButton = function(){
            if($scope.machineList.PageConfig.nowPage>1)
                $scope.machineList.PageConfig.nowPage--;
        };
      
        $scope.nextPageButton = function(){
            if($scope.machineList.PageConfig.nowPage < $scope.machineList.PageConfig.totlePage)
                $scope.machineList.PageConfig.nowPage++;
        };
      
        //展開機台上的已派工清單
        function expendMachine(index, item, event){
            
            if($scope.Mode != 'MachineExpend'){
                $scope.Mode = 'MachineExpend';
                $scope.selectMachine = item;
                $scope.selectMachine.dispatch_size = 0;
                initMachineExpend($scope.selectMachine);
                $scope.selectMachine_no = item.machine_no;
            } else if (dispatch_detail_checked.length != 0) {
                $scope.Mode = 'EditSendWork';
                $scope.selectMachine = undefined;
            }
            event.preventDefault();
        }

        var sortablList, dispatched_detail_backup;
        function initMachineExpend(item){
             // 20230301 modify by shiwl for M#0128997: 派工作业，切换派工日期，重新计算产能、已派产能、负荷率、灯号
             updateEquipmentInfo({ return_type: '0010'}); 
            // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
            if($scope.area_detail.length == 0){
                var msg = $filter('translate')('A02.alert.msg2');
                $scope.$root.showConfirm(msg, function(dialog)
                {
                   dialog.hide();
                   $scope.loadMyFavorites();
                   
                });
                return;
            }
            const content = {
                return_type: '0001',
                area_no: $scope.selectareaNo,
                lst_opno: $scope.op_group_detail.map(item => item.op_no),
                work_date: moment($scope.work_date).format("YYYY-MM-DD"),
                dispatched_condition: {
                    machine_no: item.machine_no, 
                    wo_no : $scope.assigned_wo_no || '',
                    plot_no : $scope.assigned_plot_no || ''
                },
                machine_statistics_condition : {
                    wo_no : '',
                    plot_no : ''
                },
            }
            // search({ return_type: '0001'});
            dispatch_area_info_new_get(content, function(data) {
                let dispatched_detail = data.dispatched_list;
                if(sortablList){
                    sortablList.destroy();
                    sortablList = undefined;
                    dispatched_detail_backup = undefined;
                    $scope.dispatched_detail = [];
                }
                dispatched_detail_backup = dispatched_detail.slice();
                //20220929 modify by wangzy for 0119508: 华禹彩印：派工作业处部分已派工数据无法调整顺序
                var list = [];
                list = list.concat(dispatched_detail.filter(item => item.states != '0'));
                list = list.concat(dispatched_detail.filter(item => item.states == '0'));
                // 20221104 modify by Alan for #118298: 可能是測試留下來的代碼，註解以避免錯誤
                // list.forEach(item => item.states = '0')
                $scope.dispatched_detail = list;
                dis_date_separate_action();
                if(content.dispatched_condition.wo_no == '' && content.dispatched_condition.plot_no == ''){
                    $scope.is_lock_sort = false;
                } else {
                    $scope.is_lock_sort = true;
                }
                
                // 20230210 modify by Alan for #127680: 修正排序功能
                if(!$scope.is_lock_sort){
                    $timeout(function(){
                        $('.mdd-list[list-bind=dispatched_detail] .kmi-list__row-content').attr('id', 'sortablelist');
                        sortablList = Sortable.create(document.getElementById('sortablelist'), {
                            ghostClass: 'ghost',
                            filter: '.disable',
                            handle: '.sortable-btn',
                            onEnd: function (evt) {
                                if($scope.Mode != 'EditSeq')
                                    $scope.Mode = 'EditSeq';
                                //console.log(evt);
                                if(item.dispatch_size === undefined){
                                    item.dispatch_size = 0
                                }
                                var newIndex = evt.newIndex + item.dispatch_size;
                                var oldIndex = evt.oldIndex + item.dispatch_size;
                                var chooseItem = $scope.dispatched_detail.splice(oldIndex, 1)[0];
                                //20181218 add by Dustdusk for M#: 防止沒抓到還塞進陣列內
                                if(chooseItem != undefined){
                                    $scope.dispatched_detail.splice(newIndex, 0, chooseItem);
                                    $scope.$apply();
                                }
                                
                                var list = [];
                                list = list.concat($scope.dispatched_detail.filter(item => item.states != '0'));
                                list = list.concat($scope.dispatched_detail.filter(item => item.states == '0'));
                                $timeout(() => $scope.dispatched_detail = list)
                            }
                        });
                    });
                } else {
                    $scope.$root.showToast($filter('translate')('A02.msg.cant_sort'));
                }
            })

        }
          // 20230517 modify by shiwl for M#0128997: 点开设备，显示已派工单，然后切换派工日期，已派产能对应刷新变化修改  
       function updateEquipmentInfo (option, feedback){
        let content = angular.merge(
              {
                  area_no: $scope.selectareaNo,
                  pageSetting: $scope.pageSetting,
                  lst_opno: $scope.op_group_detail.map(item => item.op_no),
                  work_date: moment($scope.work_date).format("YYYY-MM-DD"),
                  machine_statistics_condition: {
                      wo_no: "",
                      plot_no: "",
                      machine_no: "",
                      is_capacity: true
                  },
                  dispatched_condition: {
                      wo_no: "",
                      plot_no: "",
                      machine_no: "",
                  },
                  undispatched_condition: {
                      wo_no: "",
                      plot_no: "",
                  },
              },
              option
          );
          // machine_statistcs_list 設備列表
         if(content.return_type.charAt(2) === '1') {
                 content = angular.merge(
                 content,
                 {
                         machine_statistics_condition: {
                         wo_no: $scope.assigned_wo_no || "",
                         plot_no: $scope.assigned_plot_no || "",
                         machine_no: $scope.assigned_machine || "",
                         is_capacity: true
                         }
                  }
                 );
         }
         $MMWService.sendToServer({
              uri: "ServicesSTD.Module_WIP.dispatch_area_info_new_get",
              content: content,
              success: function (data) {
                   // machine_statistcs_list 設備列表
                  let result = data.machine_statistcs_list;
                  if(content.return_type.charAt(2) === '1'){
                     if(result.length){
                      // 切换日期刷新 产能：已派产能：负荷率：灯号：                                               
                       result.forEach(item=>{
                        if(item.machine_no == $scope.selectMachine_no){
                          $scope.selectMachine = item;     
                        }
                      });
                  }
                } 
                   
              }
       })
       }
        var MachineListMode = '', dispatchItem, machineList;
        $scope.itemSendwork = function(index, item){
            if(item.status == '0'){
                // 此任務在智派工納入派工，不可重複勾選！
                return $scope.$root.showAlert($filter('translate')('A02.msg.sjds_dispatch_can_not_select'));
            }
            if($scope.Mode != 'EditSendWork'){
                var feedback = function(data){
                    MachineListMode = '1';//表示派工
                    dispatchItem = item;
                    machineList = EquipmentSortForDialogAction(item,data);
                    $mddProvider.UseForm('A07_MachineList', () => {
                        $mdDialog.dialog(
                            'module/moduleA/program/A07/A07_MachineList.tmp.html',
                            MachineListController
                        );
                    });
                };
                if($scope.isLine == '1')
                    getLineMachineList(item.plot_no, item.op_no, $scope.work_date, feedback);
                else
                    getMachineList($scope.work_date, feedback);
            }
        };

        $scope.itemAccessory = function (item) {
            $scope.acc_detail = [];
            if (item.accessory_count <=0) {
                $scope.$root.showAlert($filter('translate')('A02.msg.no_accessory_no'));
                return;
            }
            $scope.acc_detail = item.lst_accessory;
            $mddProvider.UseForm('A07_AccList', () => {
                $mdDialog.dialog(
                    'module/moduleA/program/A07/A07_AccList.tmp.html',
                    AccDetailController
                );
            });
            
        };

        function AccDetailController(dialog) {
            return {
                product_acc_detail: $scope.acc_detail,
                PageConfig: { page: 0, page_count: 25 },
                order_by_mode: {name:"",sort:false},
                dispatch_filter: {},
                orderbychange: function(mode)
                {
                    if(dialog.order_by_mode.name != mode)
                    {
                        dialog.order_by_mode.name = mode;
                        dialog.order_by_mode.sort = false;
                    }
                    else
                    {
                        if (dialog.order_by_mode.sort)
                            dialog.order_by_mode.sort = false;
                        else
                            dialog.order_by_mode.sort = true;
                    }
           
                },
                getPages: function (list,PageConfig){
                    if (list) {
                        if (dialog.order_by_mode.name != "")
                            list = $filter('orderBy')(list, dialog.order_by_mode.name, dialog.order_by_mode.sort);
                        var temp_list = list.filter(function (item, index, array) {
                            var isOK = true,
                                keys = Object.keys(filterItem);
                            for (var i = 0; i < keys.length; i++) {
                                var key = keys[i];
                                if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                    if (item[key].toString().indexOf(filterItem[key]) == -1) {
                                        isOK = false;
                                        break;
                                    }
                                }
                            }
                            return isOK;
                        });
                        if (PageConfig) {
                            if (temp_list.length != 0) {
                                PageConfig.total_page = Math.ceil(temp_list.length / PageConfig.page_count);

                                if (PageConfig.page >= PageConfig.total_page) {
                                    PageConfig.page = 0;
                                }
                                var index = PageConfig.page * PageConfig.page_count;
                                return temp_list.slice(index, index + PageConfig.page_count);
                            } else {
                                PageConfig.total_page = 1;
                                PageConfig.page = 0;
                            }
                        } else {
                            return temp_list;
                        }
                    } else {

                        return list;
                    }
                },
                back: function () {
                    dialog.hide();
                }

            }
        } 

        function MachineListController(dialog){
            return {
                isLine: $scope.isLine,
                MachineListMode:MachineListMode,
                work_date:$scope.work_date,
                dispatchItem: dispatchItem,
                machineList : machineList,
                mlightColor : $scope.mlightColor,
                order_by_mode: {name:"",sort:false},
                dispatch_filter: {},
                orderbychange: function(mode)
                {
                    if(dialog.order_by_mode.name != mode)
                    {
                        dialog.order_by_mode.name = mode;
                        dialog.order_by_mode.sort = false;
                    }
                    else
                    {
                        if (dialog.order_by_mode.sort)
                            dialog.order_by_mode.sort = false;
                        else
                            dialog.order_by_mode.sort = true;
                    }
           
                },
                getMachineList: function(list, filterItem){
                    if (list) {
                        if (dialog.order_by_mode.name != "")
                            list = $filter('orderBy')(list, dialog.order_by_mode.name, dialog.order_by_mode.sort);
                        var temp_list = list.filter(function (item, index, array) {
                            var isOK = true,
                                keys = Object.keys(filterItem);
                            for (var i = 0; i < keys.length; i++) {
                                var key = keys[i];
                                if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                    if (item[key].toString().indexOf(filterItem[key]) == -1) {
                                        isOK = false;
                                        break;
                                    }
                                }
                            }
                            return isOK;
                        });
                        return temp_list;
                    } else {
                        return list;
                    }
                },
                changeDate:function(){
                    $datePicker.open(dialog.work_date,
                    function(mdDialog){
                        dialog.work_date = mdDialog.datePacker.pickDate;
                        mdDialog.hide();
                        var feedback = function(data){
                            dialog.machineList = data;
                        };
                        if($scope.isLine == '1')
                            getLineMachineList(dialog.dispatchItem.plot_no, dialog.dispatchItem.op_no, dialog.work_date, feedback);
                        else
                            getMachineList(dialog.work_date, feedback);
                    },
                    function(dialog){
                        dialog.hide();
                    },{});
                },
                prevDate:function(){
                    dialog.work_date = moment(dialog.work_date).add(-1,'d').toDate();
                    var feedback = function(data){
                        dialog.machineList = data;
                    };
                    if($scope.isLine == '1')
                        getLineMachineList(dialog.dispatchItem.plot_no, dialog.dispatchItem.op_no, dialog.work_date, feedback);
                    else
                        getMachineList(dialog.work_date, feedback);
                },
                nextDate:function(){
                    dialog.work_date = moment(dialog.work_date).add(1,'d').toDate();
                    var feedback = function(data){
                        dialog.machineList = data;
                    };
                    if($scope.isLine == '1')
                        getLineMachineList(dialog.dispatchItem.plot_no, dialog.dispatchItem.op_no, dialog.work_date, feedback);
                    else
                        getMachineList(dialog.work_date, feedback);
                },
                back : function(){
                    dialog.hide();
                },
                confirm : function(){
                    if(MachineListMode == '1'){
                        MachineListConfirmDispatch(dialog);
                    } else if(MachineListMode == '2'){
                        MachineListConfirmTransfer(dialog);
                    }
                    $scope.roll_back_all_bool = false;
                },
                _fn: {
                    ['Execute']: {
                        click: () => dialog.confirm()
                    }
                },
                // 20230425 delete by Alan for #133311: 不需要此段代碼，會造成排序、過濾異常
            };
        }

        // 20230309 modify by Alan for #127675: 修正設備列表請求參數
        // 20230203 modify by Alan for #127123: [MSSQL][sMES][在線][派工調度中心]派工作業 - 分量派工頁面顯示異常
        function getMachineList(work_date, feedback){
            var option = {
                return_type:'0010',
                area_no: $scope.selectareaNo,
                lst_opno: $scope.op_group_detail.map(item => item.op_no),
                work_date: moment(work_date).format('YYYY-MM-DD'),
                dispatched_condition: {},
                machine_statistics_condition: {
                    wo_no: "",
                    plot_no: "",
                    machine_no: "",
                    is_capacity: true
                }
            }
            dispatch_area_info_new_get(option, function(data) {
                //已派工
                if(data.machine_statistcs_list && data.machine_statistcs_list.length !=0){
                    if(feedback)
                        data.machine_statistcs_list = $filter('orderBy')(data.machine_statistcs_list,'machine_no', false); //  20240104 modify by shiwl for #0155260: 分量派工 没有进行设备编号默认排序
                        feedback(data.machine_statistcs_list);
                } else {
                    $scope.$root.showAlert($filter('translate')('A02.msg.A01first'));
                }
            })
        }

        function getLineMachineList(plot_no, op_no, work_date, feedback){
            var content = {
                form_name: 'PageNo_59',
                query_condition_info: []
            };

            content.query_condition_info.push({column_name: 'A.LOTNO', query_mode: '0', value: plot_no, merge_condition_model: 'AND'});
            content.query_condition_info.push({column_name: 'A.OPNO', query_mode: '0', value: op_no, merge_condition_model: 'AND'});
            content.query_condition_info.push({column_name: 'workdate', query_mode: '0', value: moment(work_date).format('YYYYMMDD')+'000000', merge_condition_model: 'AND'});
             // PRODUCTNO 产品编号  AREANO 区域  BASELOTNO 生产批 OPNO作业站 20231020 modify by shiwl for #0147525: 派工后改派报错，资料库执行时发生错误，ORA-01476: 除数为 0 0RA-01476: 除数为 0     
             content.query_condition_info.push({column_name: 'PRODUCTNO', query_mode: '0', value:item_no, merge_condition_model: 'AND'});
             content.query_condition_info.push({column_name: 'AREANO', query_mode: '0', value: $scope.selectareaNo, merge_condition_model: 'AND'});
             content.query_condition_info.push({column_name: 'BASELOTNO', query_mode: '0', value: plot_no, merge_condition_model: 'AND'});
             content.query_condition_info.push({column_name: 'OPNO', query_mode: '0', value: op_no, merge_condition_model: 'AND'});

            $MMWService.pageNumberInfoGet(content, function(data){
                //已派工
                if(data && data.length !=0){
                    data.forEach(function(machine){
                        machine.used_capacity = Math.round(machine._used_capacity*100 / 60)/100;
                        machine.machine_load = Math.round(machine.used_capacity*100/machine.capacity);
                        if(machine.machine_load>80)
                            machine.load_status = 'H';
                        else if(machine.machine_load>=60)
                            machine.load_status = 'M';
                        else
                            machine.load_status = 'L';
                    });
                    if(feedback)
                        feedback(data);
                } else {
                    $scope.$root.showAlert($filter('translate')('A02.msg.A01first'));
                }
            });
        }

        //派工到多機台
        function MachineListConfirmDispatch(dialog){
            var dispatchSum = 0;
            var content = {
                need_dispatch_plot_detail:[dispatchItem],
                dispatch_to:[],
                work_mode:1,
                dispatch_day:moment(dialog.work_date).format('YYYY-MM-DD')
            };

            dialog.machineList.forEach(function(machine, index){
                if(machine.inputQty != undefined && machine.inputQty != 0){
                    content.dispatch_to.push({machine_no:machine.machine_no,qty: machine.inputQty});
                    dispatchSum+= (+machine.inputQty);
                }
            });
            
            var _fn = function(request){
                dispatch_area_info_set_process(request, function(data) {
                    if(data.dispatch_msg && data.dispatch_msg.length > 0)
                    {
                        var msg = data.dispatch_msg.join("<br>")
                        $scope.$root.showConfirm(msg, function(confirm_dialog){
                            confirm_dialog.hide();
                            enforce_dispatch_action(request,function(){
                                dialog.hide();
                                $scope.work_date = dialog.work_date;
                                search({return_type:'1110'}, function() {
                                    $scope.$root.showToast(dispatchItem.plot_no+ $filter('translate')('A02.msg.saveSuccess'));
                                });
                            });
                        });
                    }
                    else
                    {
                        dialog.hide();
                        $scope.work_date = dialog.work_date;
                        search({return_type:'0110'}, function() {
                            $scope.$root.showToast(dispatchItem.plot_no+ $filter('translate')('A02.msg.saveSuccess'));
                        });
                    }
                });
            };

            if(content.dispatch_to.length == 0){
                //尚未輸入派工數量
                $scope.$root.showAlert($filter('translate')('A02.msg.no_dispatch_qty'));
            } else if(dispatchSum <= dispatchItem.qty){
                dispatch_info_calculation_process(content, function(data){
                    if(data &&  data.suggest_detail && data.suggest_detail.length > 0)
                    {
                        OpenMachineSuggestListDialog(1,content,data.suggest_detail);
                        dialog.hide();
                    }
                    else if(data && data.msg != '')
                    {
                        $scope.$root.showConfirm(data.msg, function(dialogType){
                            dialogType.hide();
                            _fn(content);
                        });
                    }
                    else
                    {
                        _fn(content);
                    };
                });
            } else {
                $scope.$root.showAlert($filter('translate')('A02.msg.numOver') + dispatchItem.qty);
            }
        }

        $scope.machineSelect = function(index, machine, event){
            if($scope.Mode == 'EditSendWork'){
                itemMutiSendwork(machine);
            } else {
                expendMachine(index, machine, event);
            }
        };

        // 20230313 modify by Alan for #129679: 清空已派查詢輸入值
        // 20230204 modify by Alan for #127154: [MSSQL][sMOM][H5][派工作业]页数错误
        $scope.closeMachine = function(){
            $scope.assigned_wo_no = "";
            $scope.assigned_plot_no = "";
            $scope.assigned_machine = "";
            $scope.Mode = '';
            $scope.selectMachine = undefined;
            if(sortablList){
                sortablList.destroy();
                sortablList = undefined;
                dispatched_detail_backup = undefined;
                $scope.dispatched_detail = [];
            }
              // 初始化页码
            $scope.pageSetting.PageNumber  = 1;
            $scope._objdispatch_detail.PageConfig.page = $scope.pageSetting.PageNumber - 1;
            dispatch_area_info_new_get({ return_type: '0110' });
        };

        //多生產批同時派工
        function itemMutiSendwork(machine){
            var content = {
                need_dispatch_plot_detail:[],
                dispatch_to:[{machine_no : machine.machine_no,}],
                work_mode:1,
                dispatch_day:moment($scope.work_date).format('YYYY-MM-DD')
            };
            // 20230911 modify by Alan for #136071: 增加跨頁選中功能
            content.need_dispatch_plot_detail = dispatch_detail_checked;
            if(content.need_dispatch_plot_detail.length <= 0)
            {
                $scope.$root.showAlert($filter('translate')('A02.msg.no_dispatch_detail'));
                return ;
            }
            if(content.need_dispatch_plot_detail.length==1){
                content.dispatch_to[0].qty = content.need_dispatch_plot_detail[0].qty;
            }

            var _fn = function(request){
                dispatch_area_info_set_process(request, function(data) {
                    if(data.dispatch_msg && data.dispatch_msg.length > 0)
                    {
                        var msg = data.dispatch_msg.join("<br>")
                        $scope.$root.showConfirm(msg, function(confirm_dialog){
                            confirm_dialog.hide();
                            enforce_dispatch_action(request,function()
                            {
                                search({ return_type:'0110' }, function() {
                                    $scope.$root.showToast(
                                        content.need_dispatch_plot_detail.length
                                        + $filter('translate')('A02.msg.sendWorkSuccess')
                                        + '['+machine.machine_no+']');
                                    $scope.Mode = '';
                                    $scope.select_all_bool = false;
                                    // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
                                    $scope.showMode = 'query';
                                });
                            });
                        });
                    }
                    else
                    {
                        search({ return_type:'0110' }, function() {
                            $scope.$root.showToast(
                                content.need_dispatch_plot_detail.length
                                + $filter('translate')('A02.msg.sendWorkSuccess')
                                + '['+machine.machine_no+']');
                            $scope.Mode = '';
                            $scope.select_all_bool = false;
                            // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
                            $scope.showMode = 'query';
                        });
                    }
                });
            };

            dispatch_info_calculation_process(content, function(data){
                if(data &&  data.suggest_detail &&  data.suggest_detail.length > 0)
                {
                    OpenMachineSuggestListDialog(0,content,data.suggest_detail);
                }
                else if(data && data.msg != '')
                {
                    $scope.$root.showConfirm(data.msg, function(dialogType){
                        dialogType.hide();
                        _fn(content);
                    });
                }
                else
                {
                    _fn(content);
                };
            });
        };
        //建議數量開窗 
        //work_mode = 0 =多筆生產批派一筆設備 
        //work_mode = 1 = 一筆生產批派多個設備
        //submit_data = 派工原始明細
        //suggest_detail = 派工建議明細
        function OpenMachineSuggestListDialog (work_mode,submit_data,suggest_detail)
        {
            $mddProvider.UseForm('A07_MachineList_suggest', () => {
                $mdDialog.dialog(
                    'module/moduleA/program/A07/A07_MachineList_suggest.tmp.html',
                    function (dialog) {
                        return {
                            suggest_detail: suggest_detail,
                            mlightColor: $scope.mlightColor,
                            submit_data: submit_data,
                            work_mode: work_mode,
                            order_by_mode: { name: "", sort: false },
                            dispatch_filter: {},
                            orderbychange: function (mode) {
                                if (dialog.order_by_mode.name != mode) {
                                    dialog.order_by_mode.name = mode;
                                    dialog.order_by_mode.sort = false;
                                }
                                else {
                                    if (dialog.order_by_mode.sort)
                                        dialog.order_by_mode.sort = false;
                                    else
                                        dialog.order_by_mode.sort = true;
                                }

                            },
                            getSuggestDetail: function (list, filterItem) {
                                if (list) {
                                    if (dialog.order_by_mode.name != "")
                                        list = $filter('orderBy')(list, dialog.order_by_mode.name, dialog.order_by_mode.sort);
                                    var temp_list = list.filter(function (item, index, array) {
                                        var isOK = true,
                                            keys = Object.keys(filterItem);
                                        for (var i = 0; i < keys.length; i++) {
                                            var key = keys[i];
                                            if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                                if (item[key].toString().indexOf(filterItem[key]) == -1) {
                                                    isOK = false;
                                                    break;
                                                }
                                            }
                                        }
                                        return isOK;
                                    });
                                    return temp_list;
                                } else {
                                    return list;
                                }
                            },
                            checkSuggestQty: function (event, item) {
                                var target = event.currentTarget;
                                angular.element(target).addClass('is-focus');
                                $calculater.open(
                                    function (num, dialog) {
                                        angular.element(target).removeClass('is-focus');
                                        dialog.hide();
                                        if ((+num) >= 0 && (+num) <= (+item.limit_qty))
                                            item.sug_qty = num;
                                        else
                                            $scope.$root.showAlert($filter('translate')('A02.suggest_list.alert2'));
                                    },
                                    //按下右上角X後會呼叫此function
                                    function (dialog) {
                                        angular.element(target).removeClass('is-focus');
                                        dialog.hide();
                                    },
                                    {
                                        defaultNum: item.sug_qty,
                                        decimal: false
                                    });
                            },
                            back: function () {
                                dialog.hide();
                            },
                            submit_action: function (request) {
                                dispatch_area_info_set_process(request, function (data) {
                                    if (data.dispatch_msg && data.dispatch_msg.length > 0) {
                                        var msg = data.dispatch_msg.join("<br>")
                                        $scope.$root.showConfirm(msg, function (confirm_dialog) {
                                            confirm_dialog.hide();
                                            enforce_dispatch_action(request, function () {
                                                search({ return_type: '0110' }, function () {
                                                    var str_array = [];
                                                    for (var i in request.dispatch_to) {
                                                        var str = request.need_dispatch_plot_detail.length +
                                                            $filter('translate')('A02.msg.sendWorkSuccess') + '[' + request.dispatch_to[i].machine_no + ']'
                                                        str_array.push(str);
                                                    }
                                                    $scope.$root.showToast(str_array.join("<br>"));
                                                    $scope.Mode = '';
                                                    $scope.select_all_bool = false;
                                                    $scope.selectRollback = 0;
                                                    if ($scope.selectMachine)
                                                        $scope.selectMachine.dispatch_size = 0;
                                                });
                                            });
                                        });
                                    }
                                    else {
                                        search({ return_type: '0110' }, function () {
                                            var str_array = [];
                                            for (var i in request.dispatch_to) {
                                                var str = request.need_dispatch_plot_detail.length +
                                                    $filter('translate')('A02.msg.sendWorkSuccess') + '[' + request.dispatch_to[i].machine_no + ']'
                                                str_array.push(str);
                                            }
                                            $scope.$root.showToast(str_array.join("<br>"));
                                            $scope.Mode = '';
                                            $scope.select_all_bool = false;
                                            $scope.selectRollback = 0;
                                            if ($scope.selectMachine)
                                                $scope.selectMachine.dispatch_size = 0;
                                        });
                                    }
                                });
                            },
                            normal_confirm: function () {

                                dialog.submit_action(dialog.submit_data);
                                dialog.hide();
                            },
                            suggest_confirm: function () {
                                var check_length = 0;
                                if (work_mode == 0) {
                                    for (var i in dialog.suggest_detail) {
                                        var op_no = dialog.suggest_detail[i].op_no;
                                        var lot_no = dialog.suggest_detail[i].lot_no;
                                        var sug_qty = dialog.suggest_detail[i].sug_qty;
                                        for (var j in dialog.submit_data.need_dispatch_plot_detail) {
                                            var org_op_no = dialog.submit_data.need_dispatch_plot_detail[j].op_no;
                                            var org_lot_no = dialog.submit_data.need_dispatch_plot_detail[j].plot_no;
                                            if (org_op_no == op_no && org_lot_no == lot_no)
                                                dialog.submit_data.need_dispatch_plot_detail[j].qty = sug_qty;
                                        }
                                    }
                                    dialog.submit_data.need_dispatch_plot_detail =
                                        dialog.submit_data.need_dispatch_plot_detail.filter(function (item) {
                                            if (item.qty > 0)
                                                return item;
                                        });
                                    check_length = dialog.submit_data.need_dispatch_plot_detail.length;
                                    if (dialog.submit_data.need_dispatch_plot_detail.length == 1) {
                                        if (dialog.submit_data.dispatch_to && dialog.submit_data.dispatch_to.length == 1) {
                                            dialog.submit_data.dispatch_to[0].qty = dialog.submit_data.need_dispatch_plot_detail[0].qty;
                                        }
                                    }
                                }
                                else if (work_mode == 1) {
                                    for (var i in dialog.suggest_detail) {
                                        var equipment_no = dialog.suggest_detail[i].equipment_no;
                                        var sug_qty = dialog.suggest_detail[i].sug_qty;
                                        for (var j in dialog.submit_data.dispatch_to) {
                                            var org_equipment_no = dialog.submit_data.dispatch_to[j].machine_no;
                                            if (equipment_no == org_equipment_no)
                                                dialog.submit_data.dispatch_to[j].qty = sug_qty;
                                        }
                                    }
                                    dialog.submit_data.dispatch_to =
                                        dialog.submit_data.dispatch_to.filter(function (item) {
                                            if (item.qty > 0)
                                                return item;
                                        });
                                    check_length = dialog.submit_data.dispatch_to.length;
                                }
                                if (check_length > 0)
                                    dialog.submit_action(dialog.submit_data);
                                else {
                                    search({ return_type: '0110' }, function () {
                                        $scope.$root.showAlert($filter('translate')('A02.suggest_list.alert1'));
                                        $scope.Mode = '';
                                        $scope.select_all_bool = false;
                                        $scope.selectRollback = 0;
                                        if ($scope.selectMachine)
                                            $scope.selectMachine.dispatch_size = 0;
                                    });
                                }
                                dialog.hide();
                            },
                            _fn: {
                                ['normal_confirm']: {
                                    click: () => dialog.normal_confirm()
                                },
                                ['suggest_confirm']: {
                                    displayText: $filter('translate')('A02.suggest_list.btn1'),
                                    click: () => dialog.suggest_confirm()
                                },
                            }
                        }
                    }
                );
            });
        }

        $scope.mlightColor = function(states){
            var lightColor;
            if(states == 'H'){
                lightColor = 'red';
            } else if(states == 'M'){
                lightColor = 'yellow';
            }if(states == 'L'){
                lightColor = 'green';
            }
            return lightColor;
        };

        $scope.confirmEditSeq = function(){
            var content = {
                machine_no :$scope.selectMachine.machine_no,
                //20220921 add by 翰鴻 for M#118068
                dispatch_day: moment($scope.work_date).format('YYYY-MM-DD'),
                dispatch_plot_detail:[]
            };
            $scope.dispatched_detail.forEach(function(detail, index){
                content.dispatch_plot_detail.push({
                    plot_no:detail.plot_no,
                    op_no:detail.op_no,
                    seq:index
                });
                detail.seq = index;
            });
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.change_dispatch_seq_process',
                content : content,
                success : function(data){
                    $scope.$root.showToast($filter('translate')('A02.msg.seqChangeSuccess'));
                    $scope.Mode = 'MachineExpend';
                    initMachineExpend($scope.selectMachine);
                }
            });
        };

        $scope.cancelEditSeq = function(){
            $scope.Mode = 'MachineExpend';
            $scope.dispatched_detail = dispatched_detail_backup.slice();
            dis_date_separate_action();
        };

        $scope.selectRollback = 0;
        $scope.detailRollback = function(index,detail){
            if(detail.status == '0'){
                // 此任務在智派工納入派工，不可重複勾選！
                return $scope.$root.showAlert($filter('translate')('A02.msg.sjds_dispatch_can_not_select'));
            }
            if($scope.Mode != 'EditSeq'){
                if(detail.isSelect){
                    detail.isSelect = undefined;
                    $scope.selectRollback--;
                }else{
                    detail.isSelect = true;
                    $scope.selectRollback++;
                }
                if($scope.selectRollback==0){
                    $scope.Mode = 'MachineExpend';
                } else {
                    $scope.Mode = 'Rollback';
                }
            }
            // 20231218 modify by wenwei for M#153623: [MSSQL] [H5][派工调度中心]派工作业，已派任务，勾选多笔已派任务，批次合并按钮显示(6009复现)
            $scope.selectSameOp = $scope.dispatched_detail.filter(item => item.isSelect == true).map(item => item.op_no).every((value, index, arr) => value === arr[0])
        };

        $scope.detailRollbackAll = function()
        {  
            if($scope.dispatched_detail.length <= 0)
                return;
            for(var i in $scope.dispatched_detail)
            {
                if($scope.roll_back_all_bool) {
                    $scope.dispatched_detail[i].isSelect = false;
                }
                else
                {
                    // 狀態 0 代表任務在智派工納入派工，不可勾選！
                    if($scope.dispatched_detail[i].status == '0') {
                        $scope.dispatched_detail[i].isSelect = false;
                    } else {
                        $scope.dispatched_detail[i].isSelect = true;
                    }
                }
            }
            if($scope.roll_back_all_bool)
            {
                $scope.roll_back_all_bool = false;
                $scope.selectRollback = 0;
                $scope.Mode = 'MachineExpend';
            }
            else
            {
                $scope.roll_back_all_bool = true;
                $scope.Mode = 'Rollback';
                $scope.selectRollback = $scope.dispatched_detail.length;
            }
        }

        function EquipmentSortAction()
        {
            //模式改變 dis order score 歸零
            if($scope.equipment_sort_mode_change)
            {
                for(var i in $scope.machine_detail)
                    $scope.machine_detail[i].dis_order_score = 0
            }
            switch($scope.equipment_sort_mode)
            {
                // 20211125 modify by Alan for #0103170: [sMES]派工作業設備順序顛倒[宏毅]
                // 修正標準預設排序(case: 0,5,6,7)
                case "0":
                    $scope.machine_detail = $filter('orderBy')($scope.machine_detail,['machine_no']);
                
                    break;
                case "1":
                    $scope.machine_detail = $filter('orderBy')($scope.machine_detail,['times','machine_no'],true);
                    break;
                case "2":
                    $scope.machine_detail = $filter('orderBy')($scope.machine_detail,['good_rate','machine_no'],true);
                    break;
                case "3":
                    $scope.machine_detail = $filter('orderBy')($scope.machine_detail,['used_load','machine_no'],true);
                    break;
                case "4":
                    $scope.machine_detail = $filter('orderBy')($scope.machine_detail,['used_load','machine_no']);
                    break;
                case "5":
                    // 20240221 modify by wenwei for M#153610
                    var dis_data = $filter('filter')($scope.dispatch_detail,{isSelect:true});
                    var has_score = false;
                    dis_data.forEach(function(item)
                    {
                        var condition = {op_no:item.op_no,product_no:item.item_no,product_ver:item.item_version};
                        var equipment_data = $filter('filter')($scope.product_detail,condition);
                        equipment_data.forEach(function(eq_item){
                            $scope.machine_detail.forEach(function(m_item)
                            {
                                if(m_item.machine_no == eq_item.equipment_no)
                                    m_item.dis_order_score += eq_item.times;
                                
                                if(m_item.dis_order_score > 0)
                                    has_score = true;
                            });
                        });
                        
                    });
                    if($scope.Mode != "EditSendWork")
                        $scope.$root.showAlert($filter('translate')('A02.equipment_sort_list.alert_1'));  
                    $scope.machine_detail = has_score 
                        ? $filter('orderBy')($scope.machine_detail, ['dis_order_score', 'machine_no'], true)
                        : $filter('orderBy')($scope.machine_detail, ['machine_no']); 
                    break;
                case "6":
                    // 20240221 modify by wenwei for M#153610
                    var dis_data = $filter('filter')($scope.dispatch_detail,{isSelect:true});
                    var has_score = false;
                    dis_data.forEach(function(item)
                    {
                        var condition = {op_no:item.op_no,product_no:item.item_no,product_ver:item.item_version};
                        var equipment_data = $filter('filter')($scope.product_detail,condition);
                        equipment_data.forEach(function(eq_item){
                            $scope.machine_detail.forEach(function(m_item)
                            {
                                if(m_item.machine_no == eq_item.equipment_no)
                                    m_item.dis_order_score += eq_item.good_rate;
                                if(m_item.dis_order_score > 0)
                                    has_score = true;
                            });
                        });
                    });
                    if($scope.Mode != "EditSendWork")
                        $scope.$root.showAlert($filter('translate')('A02.equipment_sort_list.alert_1'));
                    $scope.machine_detail = has_score 
                        ? $filter('orderBy')($scope.machine_detail, ['dis_order_score', 'machine_no'], true)
                        : $filter('orderBy')($scope.machine_detail, ['machine_no']);
                    break;
                case "7":
                    // 20240221 modify by wenwei for M#153610
                    var dis_data = $filter('filter')($scope.dispatch_detail,{isSelect:true});
                    var has_score = false;
                    dis_data.forEach(function(item)
                    {
                        var condition = {op_no:item.op_no,product_no:item.item_no,product_ver:item.item_version};
                        var equipment_data = $filter('filter')($scope.product_detail,condition);
                        equipment_data.forEach(function(eq_item){
                            $scope.machine_detail.forEach(function(m_item)
                            {
                                if(m_item.machine_no == eq_item.equipment_no)
                                    m_item.dis_order_score += eq_item.equipment_seq;
                                if(m_item.dis_order_score > 0)
                                    has_score = true;
                            });
                        });
                    });
                    if($scope.Mode != "EditSendWork")
                        $scope.$root.showAlert($filter('translate')('A02.equipment_sort_list.alert_1'));
                    $scope.machine_detail = has_score 
                        ? $filter('orderBy')($scope.machine_detail, ['dis_order_score', 'machine_no'])
                        : $filter('orderBy')($scope.machine_detail, ['machine_no']);
                    break;
            }

            $scope.getMachineList(); // 重新赋值更新设备卡片排序
        }

         //設備排序動作(改派 與 分量派)
        function EquipmentSortForDialogAction(dis_item,machine_data)
        {
             //init score for sort
             for(var i in machine_data)
                 machine_data[i].dis_order_score = 0
             if(typeof dis_item === "undefined")
                 return;
             if(typeof machine_data === "undefined" || machine_data.length <= 0)
                 return;
 
             switch($scope.equipment_sort_mode)
             {
                // 20211125 modify by Alan for #0103170: [sMES]派工作業設備順序顛倒[宏毅]
                // 修正標準預設排序(case: 0,5,6,7)
                 case "0":
                     machine_data = $filter('orderBy')(machine_data,['machine_no']);
                     break;
                 case "1":
                     machine_data = $filter('orderBy')(machine_data,['times','machine_no'],true);
                     break;
                 case "2":
                     machine_data = $filter('orderBy')(machine_data,['good_rate','machine_no'],true);
                     break;
                 case "3":
                     machine_data = $filter('orderBy')(machine_data,['used_load','machine_no'],true);
                     break;
                 case "4":
                     machine_data = $filter('orderBy')(machine_data,['used_load','machine_no']);
                     break;
                 case "5":
                         var dis_data = [dis_item];
                         var has_score = false;
                         dis_data.forEach(function(item)
                         {
                             var condition = {op_no:item.op_no,product_no:item.item_no,product_ver:item.item_version};
                             var equipment_data = $filter('filter')($scope.product_detail,condition);
                             equipment_data.forEach(function(eq_item){
                                 machine_data.forEach(function(m_item)
                                 {
                                     if(m_item.machine_no == eq_item.equipment_no)
                                         m_item.dis_order_score += eq_item.times;
                                     
                                     if(m_item.dis_order_score > 0)
                                         has_score = true;
                                 });
                             });
                             
                         });
                         machine_data = has_score 
                             ? $filter('orderBy')(machine_data, ['dis_order_score', 'machine_no'], true)
                             : $filter('orderBy')(machine_data, ['machine_no']);       
                     break;
                 case "6":
                     var dis_data = [dis_item];
                     var has_score = false;
                     dis_data.forEach(function(item)
                     {
                             var condition = {op_no:item.op_no,product_no:item.item_no,product_ver:item.item_version};
                             var equipment_data = $filter('filter')($scope.product_detail,condition);
                             equipment_data.forEach(function(eq_item){
                                 machine_data.forEach(function(m_item)
                                 {
                                     if(m_item.machine_no == eq_item.equipment_no)
                                         m_item.dis_order_score += eq_item.good_rate;
                                     if(m_item.dis_order_score > 0)
                                         has_score = true;
                                 });
                             });
                     });
                     machine_data = has_score 
                         ? $filter('orderBy')(machine_data, ['dis_order_score', 'machine_no'], true)
                         : $filter('orderBy')(machine_data, ['machine_no']);   
                     break;
                 case "7":
                     var dis_data = [dis_item];
                     var has_score = false;
                     dis_data.forEach(function(item)
                     {
                         var condition = {op_no:item.op_no,product_no:item.item_no,product_ver:item.item_version};
                         var equipment_data = $filter('filter')($scope.product_detail,condition);
                         equipment_data.forEach(function(eq_item){
                         machine_data.forEach(function(m_item)
                         {
                             if(m_item.machine_no == eq_item.equipment_no)
                                 m_item.dis_order_score += eq_item.equipment_seq;
                             if(m_item.dis_order_score > 0)
                                 has_score = true;
                             });
                         });
                     });
                     machine_data = has_score 
                         ? $filter('orderBy')(machine_data, ['dis_order_score', 'machine_no'])
                         : $filter('orderBy')(machine_data, ['machine_no']);  
                     break;
             }
             return machine_data;
        }

        //撤回
        $scope.confirmRollback = function () {
            $mddProvider.UseForm('A07_withdraw_menu', () => {
                // 20230210 modify by Alan for #127687: 補上撤回數量卡控
                $mdDialog.dialog('module/moduleA/program/A07/A07_Withdraw_menu.tmp.html', withdraw_dialog_controller);
            });
            
        };

        //撤回開窗 controller
        function withdraw_dialog_controller(dialog)
        {
            var controller = 
            {
                content:{ },
                select_list:[],
                show_data:[],
                select_label:"",
                select_machine_no:$scope.selectMachine.machine_no,
                isRunning:false,
                init:function()
                {
                    dialog.select_list = [
                        {"label":$filter('translate')('A02.with_draw.list_label_0'),"code":"0"},
                        {"label":$filter('translate')('A02.with_draw.list_label_1'),"code":"1"},
                        {"label":$filter('translate')('A02.with_draw.list_label_2'),"code":"2"},
                        {"label":$filter('translate')('A02.with_draw.list_label_3'),"code":"3"}];
                    dialog.content =
                    {
                        need_dispatch_plot_detail:[],
                        dispatch_to:[],
                        work_mode:0,
                        with_draw_mode:dialog.select_list[0].code,
                        dispatch_day:moment($scope.work_date).format('YYYY-MM-DD')
                    };
                    dialog.show_data = [];
                    dialog.isRunning = false;
                    $scope.dispatched_detail.forEach(function(detail){
                        if(detail.isSelect){
                            if(detail.states != '0'){
                                dialog.isRunning = true;
                            }
                            dialog.show_data.push({
                                plot_no:detail.plot_no,
                                op_name:detail.op_name,
                                op_no:detail.op_no,
                                limit_qty:detail.plot_qty,
                                qty:detail.plot_qty,
                                mo_no:detail.wo_no,
                                uncheck_in_qty:detail.uncheck_in_qty,
                                item_no:detail.item_no,
                                item_name:detail.item_name,
                                item_version:detail.item_version,
                                item_spec:detail.item_spec,
                                mo_no:detail.wo_no,
                                machine_no:$scope.selectMachine.machine_no,
                                plot_start_time:detail.plot_start_time,
                                plot_end_time:detail.plot_end_time
                            });
                        }
                    });
                    dialog.select_label =  dialog.select_list[0].label;
                    dialog.select_label_display = dialog.select_label;
                },
                load_withdraw_list:function()
                {
                    $scope.$root.showSelect({
                        label:"label",
                        code: 'code',
                        selectCode:dialog.select_code,
                        list: dialog.select_list,
                        confirm: function (item,select_dialog) 
                        {
                            if(dialog.content.with_draw_mode != item.code)
                            {
                                //mode change init dialog display qty
                                dialog.show_data.forEach(function(item)
                                {
                                    item.qty = item.limit_qty;
                                });
                            }
                            select_dialog.hide();
                            dialog.select_label = item.label;
                            // 20230210 modify by Alan for #127687: 補上撤回數量卡控
                            dialog.select_label_display = item.label;
                            dialog.content.with_draw_mode =item.code;
                        }
                    });
                },
                checkWithdrawQty:function(event,item)
                {
                    var target = event.currentTarget;
                    angular.element(target).addClass('is-focus');
                    $calculater.open(function(num,dialog)
                    { 
                        angular.element(target).removeClass('is-focus');
                        dialog.hide();
                        if(num > 0 && num <= item.limit_qty)
                            item.qty = num;
                        else
                            $scope.$root.showAlert($filter('translate')('A02.alert.msg1'));
                    },
                    //按下右上角X後會呼叫此function
                    function(dialog)
                    {
                        angular.element(target).removeClass('is-focus');
                        dialog.hide();
                    },
                    {
                        defaultNum : item.qty,
                        decimal : false
                    });
                },
                back: function () 
                {
                    dialog.hide();
                },
                confirm: function () 
                {
                    //20220728 modify by wangzy for 0116240: 派工撤回报错
                    //for循环取值不对，应该取length才对，导致赋值need_dispatch_plot_detail异常
                    for (var i = 0; i < dialog.show_data.length; i++)
                    {
                        dialog.content.need_dispatch_plot_detail.push({
                            plot_no:dialog.show_data[i].plot_no,
                            op_no:dialog.show_data[i].op_no,
                            qty:dialog.show_data[i].qty,
                            mo_no:dialog.show_data[i].mo_no,
                            machine_no:dialog.show_data[i].machine_no,
                            plot_start_time:dialog.show_data[i].plot_start_time,
                            plot_end_time:dialog.show_data[i].plot_end_time
                        });
                    }
                    var _fn = function(){
                        dispatch_area_info_set_process(dialog.content, function(data) {
                            if(data.dispatch_msg && data.dispatch_msg.length > 0)
                            {
                                var msg = data.dispatch_msg.join("<br>")
                                $scope.$root.showConfirm(msg, function(confirm_dialog)
                                {
                                    confirm_dialog.hide();
                                    enforce_dispatch_action(request,function()
                                    {
                                        search({ return_type:'0110' }, function() {
                                            $scope.$root.showToast(
                                                $filter('translate')('A02.msg.rollbackSuccess.1')
                                                + $scope.selectRollback
                                                + $filter('translate')('A02.msg.rollbackSuccess.2')
                                            );
                                            $scope.Mode = 'MachineExpend';
                                            $scope.selectRollback = 0;
                                            $scope.roll_back_all_bool = false;
                                            $scope.selectMachine.dispatch_size = 0;
                                            var machine = $filter('filter')($scope.machine_detail, {machine_no:$scope.selectMachine.machine_no});
                                            if(machine!=undefined && machine.length > 0){
                                                $scope.selectMachine = machine[0];
                                            }
                                            initMachineExpend($scope.selectMachine);
                                        });
                                    });
                                });
                            }
                            else
                            {
                                search({ return_type:'0110' }, function() {
                                    $scope.$root.showToast(
                                        $filter('translate')('A02.msg.rollbackSuccess.1')
                                        + $scope.selectRollback
                                        + $filter('translate')('A02.msg.rollbackSuccess.2')
                                    );
                                    $scope.Mode = 'MachineExpend';
                                    $scope.selectRollback = 0;
                                    $scope.roll_back_all_bool = false;
                                    $scope.selectMachine.dispatch_size = 0;
                                    var machine = $filter('filter')($scope.machine_detail, {machine_no:$scope.selectMachine.machine_no});
                                    if(machine!=undefined && machine.length > 0){
                                        $scope.selectMachine = machine[0];
                                    }
                                    initMachineExpend($scope.selectMachine);
                                });
                            }
                        });
                    };
                    if(dialog.isRunning)
                    {
                        $scope.$root.showConfirm($filter('translate')('A02.msg.plot_still_running'), function(confirm_dialog){
                            confirm_dialog.hide();
                            dispatch_info_calculation_process(dialog.content, function(data){
                                if(data && data.msg != '')
                                {
                                    $scope.$root.showConfirm(data.msg, function(dialogType){
                                        dialogType.hide();
                                        _fn();
                                    });
                                }
                                else
                                {
                                    _fn();
                                };
                            });
                        });
                    } 
                    else 
                    {
                        _fn();
                    }
                    dialog.hide();
                },
                _fn: {
                    ['Execute']: {
                        click: () => dialog.confirm()
                    }
                },
                _event: {
                    ['select_label']: {
                        click: (select_label) => dialog.load_withdraw_list()
                    }
                }
            };
            return controller;
        };

        //取消撤回/移轉
        $scope.cancelRollback = function(){
            $scope.dispatched_detail.forEach(function(detail){
                detail.isSelect = undefined;
            });
            $scope.selectRollback = 0;
            $scope.Mode = 'MachineExpend';
            $scope.roll_back_all_bool = false;
        };

        //改派
        $scope.confirmTransfer = function(){
            var transferItem,
                feedback = function(data){
                    dispatchItem = transferItem;
                    MachineListMode = '2';//轉移
                    machineList = EquipmentSortForDialogAction(dispatchItem, data);
                    $mddProvider.UseForm('A07_MachineList', () => {
                        $mdDialog.dialog(
                            'module/moduleA/program/A07/A07_MachineList.tmp.html',
                            MachineListController
                        );
                    });
                    
                };
            // 取出勾選的已派生產批
            $scope.dispatched_detail.forEach(function(detail){
                if(detail.isSelect){
                    transferItem = detail;
                    transferItem.qty = detail.plot_qty;
                    transferItem.machine_no = $scope.selectMachine.machine_no;
                }
            });
            if(transferItem){
                if($scope.isLine == '1'){
                    item_no = transferItem.item_no;
                    getLineMachineList(transferItem.plot_no, transferItem.op_no, $scope.work_date, feedback);
                } else{
                    getMachineList($scope.work_date, feedback);
                }
                    
            }
        };

        // 批次合併
        $scope.confirmBatchMerge = function(){
            $mddProvider.UseForm('A07_batchMerge', () => {
                $mdDialog.dialog(
                    'module/moduleA/program/A07/A07_BatchMerge.tmp.html',
                    function(dialog){
                        return {
                            batchMerge_input: '',
                            back : function(){
                                dialog.hide();
                            },
                            confirm: function(){
                                var content = {
                                    work_mode: 3,
                                    dispatch_day: moment($scope.work_date).format('YYYY-MM-DD'),
                                    machine_detail: [{
                                        machine_no: $scope.selectMachine.machine_no,
                                        dispatched_detail: []
                                    }],
                                    need_dispatch_plot_detail:[]
                                };
    
                                $scope.dispatched_detail.forEach(function(item){
                                    if(item.isSelect)
                                    {
                                        item.qty = (+item.plot_qty);
                                        item.batch_mark = dialog.batchMerge_input;
                                        content.machine_detail[0].dispatched_detail.push(item);
                                        content.need_dispatch_plot_detail.push(item);
                                    }
                                });
    
                                dispatch_area_info_set_process(content, function(data) {
                                    if(data.dispatch_msg && data.dispatch_msg.length > 0)
                                    {
                                        var msg = data.dispatch_msg.join("<br>")
                                        $scope.$root.showConfirm(msg, function(confirm_dialog)
                                        {
                                            confirm_dialog.hide();
                                            enforce_dispatch_action(request,function()
                                            {
                                                dialog.hide();
                                                dialog.batchMerge_input = '';
                                            });
                                        });
                                    }
                                    else
                                    {
                                        dialog.hide();
                                        dialog.batchMerge_input = '';
                                    }
                                });
                            },
                            _fn: {
                                ['Execute']: {
                                    click: () => dialog.confirm()
                                }
                            }
                        }
                    }
                )
            });
        };

        // 刪除批次合併註記
        $scope.deleteBatchMergeMark = function(detail){
            detail.batch_mark = '';
            var content = {
                work_mode: 3,
                dispatch_day: moment($scope.work_date).format('YYYY-MM-DD'),
                machine_detail: [{
                    machine_no: $scope.selectMachine.machine_no,
                    dispatched_detail: [detail]
                }],
                need_dispatch_plot_detail: [detail]
            };
            dispatch_area_info_set_process(content, function(data, response) {
                if(response.isSuccess){
                    // 批次合併註記刪除成功
                    $scope.$root.showToast($filter('translate')('A02.msg.batchMerge_delete_success'));
                }
            });
        };

        function MachineListConfirmTransfer(dialog){
            var dispatchSum = 0;
            var content = {
                need_dispatch_plot_detail:[dispatchItem],
                dispatch_to:[],
                work_mode:2,
                transfer_day:moment(dialog.work_date).format('YYYY-MM-DD'),//要轉移的目標日期
                dispatch_day:moment($scope.work_date).format('YYYY-MM-DD')//派工當時的日期
            };
            dialog.machineList.forEach(function(machine, index){
                if(machine.inputQty != undefined && machine.inputQty != 0){
                    content.dispatch_to.push({machine_no:machine.machine_no,qty: machine.inputQty});
                    dispatchSum+= (+machine.inputQty);
                }
            });

            var _fn = function(request){
                dispatch_area_info_set_process(request, function(data) {
                    if(data.dispatch_msg && data.dispatch_msg.length > 0)
                    {
                        var msg = data.dispatch_msg.join("<br>")
                        $scope.$root.showConfirm(msg, function(confirm_dialog)
                        {
                            confirm_dialog.hide();
                            enforce_dispatch_action(request,function()
                            {   
                                dialog.hide();
                                search({ return_type:'0110' }, function() {
                                    $scope.$root.showToast(dispatchItem.plot_no+$filter('translate')('A02.msg.transSuccess'));
                                    $scope.Mode = 'MachineExpend';
                                    $scope.selectRollback = 0;
                                    $scope.selectMachine.dispatch_size = 0;
                                    var machine = $filter('filter')($scope.machine_detail, {machine_no:$scope.selectMachine.machine_no});
                                    if(machine!=undefined && machine.length > 0){
                                        $scope.selectMachine = machine[0];
                                    }
                                    initMachineExpend($scope.selectMachine);
                                });
                            });
                        });
                    }
                    else
                    {
                        dialog.hide();
                        search({ return_type:'0110' }, function() {
                            $scope.$root.showToast(dispatchItem.plot_no+$filter('translate')('A02.msg.transSuccess'));
                            $scope.Mode = 'MachineExpend';
                            $scope.selectRollback = 0;
                            $scope.selectMachine.dispatch_size = 0;
                            var machine = $filter('filter')($scope.machine_detail, {machine_no:$scope.selectMachine.machine_no});
                            if(machine!=undefined && machine.length > 0){
                                $scope.selectMachine = machine[0];
                            }
                            initMachineExpend($scope.selectMachine);
                        });
                    }
                });
            };

            if(content.dispatch_to.length == 0){
                //尚未輸入派工數量
                $scope.$root.showAlert($filter('translate')('A02.msg.no_dispatch_qty'));
            } else if(dispatchSum <= dispatchItem.qty){
                dispatch_info_calculation_process(content, function(data){
                    if(data &&  data.suggest_detail && data.suggest_detail.length > 0)
                    {
                        OpenMachineSuggestListDialog(1,content,data.suggest_detail);
                        dialog.hide();
                    }
                    else if(data && data.msg != '')
                    {
                        $scope.$root.showConfirm(data.msg, function(dialogType){
                            dialogType.hide();
                            _fn(content);
                        });
                    }
                    else
                    {
                        _fn(content);
                    };
                });
            } else {
                $scope.$root.showAlert($filter('translate')('A02.msg.transOver') + dispatchItem.qty);
            }
        }

        function dispatch_info_calculation_process(content, callback){
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.dispatch_info_calculation_process',
                content : content,
                success: function(data){
                    if(callback)
                        callback(data);
                }
            });
        };
        
        // 20230911 modify by Alan for #136071: 換頁不清除勾選狀態
        // 20221117 modify by shiwl for M#18991: 实体分页上一页和下一页
        $scope.previous = function () {
            search({ return_type: '0110', cleanCache: false });
        };

        $scope.next = function () {
            search({ return_type: '0110', cleanCache: false });
        };

        // 20230325 modify by Alan for #129909: 修正過濾功能
        // 20230221 modify by Alan for #128323: 修正過濾功能
        $scope.getPages = function(list, PageConfig, filterItem,header){
            if(list){
               if( header && header.code != "")
                list =  $filter('orderBy')(list,header.code,header.order);
               return temp_list = list.filter(function(item, index, array){
                    var isOK = true,
                        keys = Object.keys(filterItem);
                    for(var i =0; i<keys.length;i++){
                        var key = keys[i];
                        if(isOK && item[key]!=null && filterItem[key] && filterItem[key]!=''){
                            if(item[key].toString().indexOf(filterItem[key]) == -1){
                                isOK = false;
                                break;
                            }
                        }
                    }
                    return isOK;
                });
            } else {
                if($scope.order_by_mode.name != ""){
                        list =  $filter('orderBy')(list,$scope.order_by_mode.name,$scope.order_by_mode.sort);
                        return list;
                } else {
                        return list;
                }
               
            }
        };

        function enforce_dispatch_action(request,feedback)
        {
            request.enforce_dispatch_msg = "1";
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                content : request,
                success : function(data)
                {
                    feedback();
                }
            });
        }

        function dispatch_area_info_set_process(content, feedback)
        {
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                content : content,
                success : function(data, response)
                {
                    feedback(data, response);
                },
                error : function(data, response)
                {
                    // 20230911 modify by Alan for #136071: 後端卡控時，退出勾選狀態
                    $scope.$root.showAlert(data.ExceptionMessage);
                    $scope.Mode = '';
                    // 送出的數據可能已經配派掉了，所以要重新查詢
                    search({ return_type:'0110' })
                }
            });
        }

        $scope._event = {
            ['selectareaName']: {
                click: () => $scope.loadAreaList()
            },
            ['selectWorkStationName']: {
                click: () => $scope.loadWorkStationList()
            },
            ['equipment_sort_mode_label']: {
                changed: (item) => {
                    $scope.equipment_sort_mode_change = ($scope.equipment_sort_mode != item.name);
                    $scope.equipment_sort_mode = item.name;
                    EquipmentSortAction();
                }
            },
            ['unassigned_wo_no']: {
                isShown: 'Y'
            },
            ['unassigned_plot_no']: {
                isShown: 'Y'
            },
            ['dispatch_detail']: {
                isShown: 'Y',
                selectAll: (list) => $scope.itemAllAction(),
                select: (item, args) => $scope.itemSelect(undefined, item),
                 // 20230626 modify by shiwl for #0138789: 派工作业，点击工单号排序不生效问题
                getPages: (list, PageConfig, filterItem, header) => $scope.getPages(list, PageConfig, {}, header)
            },
            ['machine_panel']: {
                isShown: 'Y'
            },
            // 已派設備訊息
            ['machine_display']: {
                isShown: 'N'
            },
            ['capacity_display']: {
                isShown: 'N'
            },
            ['used_capacity_display']: {
                isShown: 'N'
            },
            ['machine_load_display']: {
                isShown: 'N'
            },
            ['select_machine_light']: {
                isShown: 'N'
            },
            // 已派訊息
            ['dispatched_detail']: {
                isShown: 'N',
                selectAll: () => $scope.detailRollbackAll(),
                select:(item, args) => $scope.detailRollback(undefined, item),
            },
            ['A07_machine_panel']: {
                isShown: 'Y'
            },
            ['dispatched_detail_footer']: {
                isShown: 'N'
            }
        }

        $scope._fn = {
            // 20230601 add by Alan for #124840: 實體分頁排序功能
            ['setting']: {
                click: () => {
                    // 20230911 modify by Alan for #136071: 勾選狀態不可變更排序
                    if ($scope.Mode === 'EditSendWork') {
                        $scope.$root.showAlert($filter('translate')('A07.showAlert.cant_change_sort'));
                        return;
                    }
                    // 取得未派顯示欄位
                    const columns = [];
                    for(let key in $scope._event) {
                        // 要過濾的欄位
                        const hiddenColumns = ['dispatch_detail.acc_detail', 'dispatch_detail.item_send_work', 'dispatch_detail.lst_accessory'];
                        const isShow =
                            key.includes("dispatch_detail.") &&
                            !hiddenColumns.includes(key) &&
                            $scope._event[key].isShown != "N";
                        if (isShow) {
                            columns.push({
                                code: key.split(".")[1],
                                label: $scope._event[key].displayText,
                            });
                        }
                    }
                    $mdDialog.serviceDialog('customOrderService', {
                        listName: 'dispatch_detail',
                        columns: columns,
                        callback: function() {
                            // 更新未派訊息
                            search({ return_type: '0110' })
                        }
                    });
                }
            },
            ['favorite']: {
                click: () => $scope.loadMyFavorites()
            },
            ['unassigned_search']: {
                isShown: 'Y'
            },
            ['unassigned_clear']: {
                isShown: 'Y'
            },
            ['unassigned_search']: {
                click: () => $scope.unassigned_search()
            },
            ['unassigned_clear']: {
                click: () => $scope.unassigned_clear()
            },
            ['assigned_search']: {
                click: () => $scope.assigned_search()
            },
            ['assigned_clear']: {
                click: () => $scope.assigned_clear()
            },
            ['print']: {
                isShown: 'N',
                click: () => $scope.preview()
            },
        }

        // 20230204 modify by Alan for #127154: [MSSQL][sMOM][H5][派工作业]页数错误 
        $scope.$watch('_objdispatch_detail.PageConfig.page', (newVal, oldVal) => {
            if (newVal == oldVal) return;
            $scope.pageSetting.PageNumber = newVal + 1;
            if(newVal > oldVal){
                $scope.next();
            } else {
                $scope.previous();
            }
        }, true);
        $scope.$watch('showMode', (newVal) => {
            $scope._fn['print'].isShown = newVal === 'preview' ? 'Y' : 'N'
            if(newVal === 'print'){
                $scope._fn['print'].isShown = 'Y';
                $('.mdd-layout').addClass('pdf-open');
            } else {                
                $('.mdd-layout').removeClass('pdf-open');
            }
        });
        $scope.$watch('selectareaName', (newVal) => $scope.selectareaName_display = newVal);
        $scope.$watch('selectWorkStationName', (newVal) => $scope.selectWorkStationName_display = newVal);
        $scope.$watch('select_all_bool', (newVal) => $scope._event['dispatch_detail'].isSelectAll = newVal);
        $scope.$watch('roll_back_all_bool', (newVal) => $scope._event['dispatched_detail'].isSelectAll = newVal);
        $scope.$watch('selectMachine',(newVal) => {
            if(newVal){
                newVal.machine_display = `${ newVal.machine_no } (${ newVal.machine_name })`;
                newVal.capacity_display = `${ newVal.capacity_show }HR`;
                newVal.used_capacity_display = `${ newVal.used_capacity_show }HR`;
                newVal.machine_load_display = `${ newVal.machine_load  }%`;
            }
        })
        $scope.$watch('Mode', (newVal) => {
            if(newVal === 'MachineExpend' || newVal === 'EditSeq' || newVal === 'Rollback') {
                $scope._event['unassigned_wo_no'].isShown = 'N';
                $scope._event['unassigned_plot_no'].isShown = 'N';
                $scope._fn['unassigned_search'].isShown = 'N';
                $scope._fn['unassigned_clear'].isShown = 'N';

                $scope._event['dispatch_detail'].isShown = 'N';
                $scope._event['machine_panel'].isShown = 'N';
                
                $scope._event['machine_display'].isShown = 'Y';
                $scope._event['capacity_display'].isShown = 'Y';
                $scope._event['used_capacity_display'].isShown = 'Y';
                $scope._event['machine_load_display'].isShown = 'Y';
                $scope._event['select_machine_light'].isShown = 'Y';

                $scope._event['dispatched_detail'].isShown = 'Y';
                $scope._event['A07_machine_panel'].isShown = 'N';
                $scope._event['dispatched_detail_footer'].isShown = 'Y';

                $scope._event['selectareaName'].isDisabled = 'Y';
                $scope._event['selectWorkStationName'].isDisabled = 'Y';
                $scope._event['equipment_sort_mode_label'].isDisabled = 'Y';
                
                $('.mdd-layout').addClass('dispatched');
            } else {
                $scope._event['unassigned_wo_no'].isShown = 'Y';
                $scope._event['unassigned_plot_no'].isShown = 'Y';
                $scope._fn['unassigned_search'].isShown = 'Y';
                $scope._fn['unassigned_clear'].isShown = 'Y';

                $scope._event['dispatch_detail'].isShown = 'Y';
                $scope._event['machine_panel'].isShown = 'Y';

                $scope._event['machine_display'].isShown = 'N';
                $scope._event['capacity_display'].isShown = 'N';
                $scope._event['used_capacity_display'].isShown = 'N';
                $scope._event['machine_load_display'].isShown = 'N';
                $scope._event['select_machine_light'].isShown = 'N';

                $scope._event['dispatched_detail'].isShown = 'N';
                $scope._event['A07_machine_panel'].isShown = 'Y';
                $scope._event['dispatched_detail_footer'].isShown = 'N';

                $scope._event['selectareaName'].isDisabled = 'N';
                $scope._event['selectWorkStationName'].isDisabled = 'N';
                $scope._event['equipment_sort_mode_label'].isDisabled = 'N';

                $('.mdd-layout').removeClass('dispatched');
            }
        });

        // 20230911 modify by Alan for #136071: 增加跨頁選中功能
        // 篩選時，清空已選中的項目
        $scope.$watch('_objdispatch_detail.filterColumns', (newVal, oldVal) => {
            dispatch_detail_checked = [];
            $scope.dispatch_detail.forEach((item) => item.isSelect = false);
            $scope.Mode = '';
            $scope.select_all_bool = false;
        }, true);
    }
];});
